複数フラグ判定を行うenum実装とそれのUnityTestRunnerコード
ゲームでよくある武器の属性をC#のenumで実装する時、こんな感じで書ける。
using System; [Flags] public enum WeaponElement { Fire = 1, Water = 1 << 1, Earth = 1 << 2, Wind = 1 << 3 } public static class WeaponElementExtension { public static bool IsSatisfy(this WeaponElement e, int checkBit) { return ((int) e & checkBit) != 0; } }
bit flag で宣言してるのは、属性判定を行う時に便利なケースがあるから。 例えば、何かしらのスキルや装備の効果で、「炎のみ」「炎と水」「全ての属性に対して〜」などの判定バリエーションがある時、一つのプロパティでそれらを判定できる。
上のenum実装がちゃんと動作するかどうかは、Unity Test Runner を書いておけば確認できるし、今後も自動テストとして運用できるようになる。
UnityTestRunner に作り方については、下記サイトが参考になった。
今回作成したTestコードは下記のとおり。属性チェック用のメソッドがちゃんと期待通りの動きをするかテストする。
using NUnit.Framework; public class WeaponElementTest { [Test] public void IsSatisfyTest() { int checkFire = 1; Assert.IsTrue(WeaponElement.Fire.IsSatisfy(checkFire)); int checkWater = 1 << 1; Assert.IsTrue(WeaponElement.Water.IsSatisfy(checkWater)); int checkEarth = 1 << 2; Assert.IsTrue(WeaponElement.Earth.IsSatisfy(checkEarth)); int checkWind = 1 << 3; Assert.IsTrue(WeaponElement.Wind.IsSatisfy(checkWind)); int checkFireAndEarth = checkFire + checkEarth; Assert.IsTrue(WeaponElement.Fire.IsSatisfy(checkFireAndEarth)); Assert.IsFalse(WeaponElement.Water.IsSatisfy(checkFireAndEarth)); Assert.IsTrue(WeaponElement.Earth.IsSatisfy(checkFireAndEarth)); Assert.IsFalse(WeaponElement.Wind.IsSatisfy(checkFireAndEarth)); int checkAllElement = checkFire + checkWater + checkEarth + checkWind; Assert.IsTrue(WeaponElement.Fire.IsSatisfy(checkAllElement)); Assert.IsTrue(WeaponElement.Water.IsSatisfy(checkAllElement)); Assert.IsTrue(WeaponElement.Earth.IsSatisfy(checkAllElement)); Assert.IsTrue(WeaponElement.Wind.IsSatisfy(checkAllElement)); } }
作成したTestを実行するには、下記Windowを開いて
今回はEditModeのTestとして作成したので、EditModeのタブで Play all を実行すればテスト実行できる。
Unityのコードを普通に再生してテストとかすると非常に時間がかかるので、このテスト機能はとても嬉しい。