コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】指定された値をリテラル付きの文字列に変換する関数

C#

概要 private static string ToLiteralString( object value ) { if ( value == null ) return "null"; if ( value is bool boolValue ) return boolValue ? "true" : "false"; if ( value is float floatValue ) return $"{floatValue}f"; if ( value is lo…

【C#】構造体のフィールドに初期値を設定する代替案

C#

概要 C# 9.0 までは引数なしコンストラクタを定義できないため 構造体のフィールドに初期値を設定できない 代替案としてフィールドを nullable にして プロパティの getter でフィールドが null なら初期値を設定する方法がある using UnityEngine; public s…

【C#】指定した値が組み込みの値型かどうかを確認する方法

C#

概要 // すべて True Debug.Log( typeof( bool ).IsValueType ); Debug.Log( typeof( byte ).IsValueType ); Debug.Log( typeof( sbyte ).IsValueType ); Debug.Log( typeof( char ).IsValueType ); Debug.Log( typeof( decimal ).IsValueType ); Debug.Log(…

【C#】指定した値が配列かどうかを確認する方法

C#

概要 var array1 = new int[ 0 ]; var array2 = new string[ 0 ]; var array3 = new Vector3[ 0 ]; Debug.Log( array1.GetType().IsArray ); Debug.Log( array2.GetType().IsArray ); Debug.Log( array3.GetType().IsArray ); 参考サイト様

【C#】指定した値が Dictionary かどうかを確認する方法

C#

概要 var dictionary1 = new Dictionary<int, string>(); var dictionary2 = new Dictionary<int, Vector3>(); Debug.Log( typeof( Dictionary<,> ).IsAssignableFrom( dictionary1.GetType().GetGenericTypeDefinition() ) ); Debug.Log( typeof( Dictionary<,> ).IsAssignableFrom( di</int,></int,>…

【C#】指定した値が List かどうかを確認する方法

C#

概要 参考サイト様

【C#】文字列から HTML のタグを削除する例

C#

概要 var text = Regex.Replace( text, "<.*?>", string.Empty );

【C#】2 つの配列の要素をインデックス同士で紐付けて Tuple にまとめる拡張メソッド

概要 using System.Collections.Generic; namespace Kogane { public static class SequenceJoinTupleExtensionMethods { public static (T1, T2)[] JoinTuple<T1, T2>( this T1[] self, T2[] other ) { var count = self.Length; var result = new (T1, T2)[ count </t1,>…

【C#】条件を満たす場合にのみ Prepend する拡張メソッド

概要 using System.Collections.Generic; using System.Linq; namespace Kogane { public static class EnumerableExtensionMethods { public static IEnumerable<T> PrependIf<T> ( this IEnumerable<T> self, bool conditional, T element ) { return !conditional </t></t></t>…

【C#】System.Text.Json で列挙型を文字列でシリアライズする方法

C#

概要 using System.Text.Json; using UnityEngine; public enum CharacterType { NONE, PLAYER, ENEMY, } public class Example : MonoBehaviour { private void Start() { var data = new { characterType = CharacterType.PLAYER }; Debug.Log( JsonSerial…

【Unity】Unity 2021 以降で GetHashCode を簡単に実装する方法

C#

概要 System.HashCode を使用すると GetHashCode を簡単に実装できる using System; using UnityEngine; public sealed class Character { public int Id { get; } public string Name { get; } public Character ( int id, string name ) { Id = id; Name =…

【C#】指定した倍数で四捨五入のように丸める関数

C#

ソースコード public static class MathUtils { public static double RoundByMultiple( double value, double unit ) { return Math.Round( value / unit ) * unit; } } 使用例 Console.WriteLine( MathUtils.RoundByMultiple( 0.26, 0.25 ) ); // 0.25 Con…

【C#】Flags が付いている列挙型で ALL を表現する方法

C#

概要 [Flags] public enum PokemonType { FIRE = 1 << 0, WATER = 1 << 1, GRASS = 1 << 2, ALL = FIRE | WATER | GRASS, } 上記のように Flags が付いている列挙型で ALL を表現している場合、 [Flags] public enum PokemonType { FIRE = 1 << 0, WATER = 1 …

【C#】指定したパスのすべての親フォルダのパスを取得する方法

C#

ソースコード private static IEnumerable<string> GetParentDirectories( string path ) { while ( true ) { var directoryName = Path.GetDirectoryName( path ); if ( string.IsNullOrWhiteSpace( directoryName ) ) yield break; yield return directoryName; pa</string>…

【C#】値をスワップする拡張メソッドを自作する

C#

ソースコード public static class GenericExtensions { public static void Swap<T>( ref this T a, ref T b ) where T : struct { var tmp = a; a = b; b = tmp; } } 使用例 using UnityEngine; public class Example : MonoBehaviour { private void Awake()</t>…

【C#】値をスワップする関数を自作する

C#

ソースコード public static class GenericUtils { public static void Swap<T>( ref T a, ref T b ) { var tmp = a; a = b; b = tmp; } } 使用例 using UnityEngine; public class Example : MonoBehaviour { private void Awake() { int a = 1; int b = 2; Ge</t>…

【C#】タプルで値をスワップする方法

C#

概要 using UnityEngine; public class Example : MonoBehaviour { private void Awake() { int a = 1; int b = 2; ( a, b ) = ( b, a ); } }

【C#】glob によるパターンマッチングを行う方法

はじめに GitHub で公開されている上記のライブラリを使用すると C# で glob によるパターンマッチングができるようになる 使用例 static クラスを使用する方法 var isMatch = Glob.IsMatch ( input: "Assets/Textures/example.png", pattern: "Assets/Textu…

【C#】glob のパターンマッチングを正規表現で使用する例

C#

概要 var globPattern = "Assets/Textures/*.png"; var pattern = Regex .Escape( globPattern ) .Replace( @"\*", ".*" ) .Replace( @"\?", "." ) ; var isMatch = Regex.IsMatch ( input: "Assets/Textures/example.png", pattern: pattern ); Console.Wri…

【C#】XML のすべての要素を読み込むサンプル

C#

概要 using System; using System.Xml.Linq; class Program { static void Main() { var document = XDocument.Load( "【XML のファイルパス】" ); foreach ( var xElement in document.Descendants().Elements() ) { Console.WriteLine( xElement.Name ); }…

【C#】var sw = new Stopwatch(); sw.Start(); をまとめて行う Stopwatch.StartNew

C#

概要 using System.Diagnostics; using System.Threading.Tasks; using UnityEngine; public class Example : MonoBehaviour { private async void Start() { var sw = new Stopwatch(); sw.Start(); await Task.Delay( 1000 ); sw.Stop(); print( sw.Elapse…

【C#】File.Copy で DirectoryNotFoundException が出る場合

C#

概要 DirectoryNotFoundException: Could not find a part of the path "XXX" or "YYY" File.Copy した時に DirectoryNotFoundException が出る状況に遭遇した 第2引数の destFileName に指定しているファイルパスが長すぎることが原因だった ファイルパスを…

【C#】文字列に含まれている改行やタブ文字などのエスケープ文字を変換する方法

C#

概要 var str = "{\n\t\\\"id\\\":25,\n\t\\\"name\\\":\\\"\\u30d4\\u30ab\\u30c1\\u30e5\\u30a6\\\"\n}"; Debug.Log( Regex.Unescape( str ) ); { "id":25, "name":"ピカチュウ" } Regex.Unescape を使用する

【C#】ファイルが gzip で圧縮されているかどうかを確認する関数

C#

概要 public static bool IsGZip( byte[] bytes ) { return 2 <= bytes.Length && bytes[ 0 ] == 31 && bytes[ 1 ] == 139; }

【C#】Windows Forms の InitializeComponent で User Control の new が消えてしまう場合

C#

概要 User Control を継承したクラスのコンストラクタが public 以外になっていると Windows Forms の InitializeComponent で User Control の new が消えてしまう

【C#】シーケンスの要素が重複している場合 true を返す拡張メソッド

ソースコード using System; using System.Collections.Generic; using System.Linq; public static class IEnumerableExt { public static bool HasDuplication<TKey, TSource> ( this IEnumerable<TSource> self, Func<TSource, TKey> keySelector ) { return self .GroupBy( keySelector ) .Any( </tsource,></tsource></tkey,>…

【C#】明示的なインターフェイスの実装

C#

概要 public interface IHoge { void Hoge(); } public class Hoge1 : IHoge { // 通常の実装 public void Hoge() { } } public class Hoge2 : IHoge { // 明示的なインターフェイスの実装 void IHoge.Hoge() { } } public class Program { private static v…

【C#】デバッグビルドだとやけに動作が遅い場合のメモ

C#

概要 リリースビルドだと3秒で終わる処理が デバッグビルドだと5分以上かかる減少に遭遇した Visual Studio メニューの「デバッグ > すべてのブレークポイントの削除」を選択したら デバッグビルドでも処理が5秒くらいで終わるようになった 条件付きブレーク…

【C#】using ステートメントに指定した変数が null でも抜ける時に例外は発生しない

C#

概要 using System; using UnityEngine; internal sealed class Hoge : IDisposable { public void Dispose() { Debug.Log( "ピカチュウ" ); } } internal class Example : MonoBehaviour { private void Start() { using ( Hoge hoge = null ) { } } } 上記…

【C#】ショートカット(.lnk)のリンク先のパスを取得する方法

C#

概要 Visual Studio のプロジェクトの「参照」を右クリックして「参照の追加」を選択して 「COM」を選択して「Windows Script host Object Model」をチェックして「OK」を押します using IWshRuntimeLibrary; using System; internal static class Program {…