[Unity] UnityActionの記述サンプル

実際の記述例

今回は、UnityActionの具体的な記述サンプルを記載しておこうと思います。


KindleのUnity本一覧

using を指定しておこう

using UnityEngine.Events;
UnityEngine.Eventsの仲間なので、usingで指定しておきましょう。

プロパティとしての宣言

public UnityAction voidAction { get; set; }
public UnityAction<int> intAction { get; set; }
public UnityAction<int, string> intStringAction { get; set; }
public UnityAction<int, string, Vector3> intStringVector3Action { get; set; }
public UnityAction<int, string, Vector3, MonoBehaviour> intStringVector3BehaviourAction { get; set; }
こんな感じに引数の数に応じて宣言します。
引数の数は0~4までです。
ちなみに、System.Actionだと、もっと多くの引数が指定できますよ。
戻り値が欲しい場合は、System.Funcです。

処理の登録

voidAction = () => Debug.Log("voidAction");
intAction = (arg0) => Debug.Log("intAction");
intStringAction = (arg0, arg1) => Debug.Log("intStringAction");
intStringVector3Action = (arg0, arg1, arg2) => Debug.Log("intStringVector3Action");
intStringVector3BehaviourAction = (arg0, arg1, arg2, arg3) => Debug.Log("intStringVector3BehaviourAction");
ラムダ式だとこんな感じです。
複数行だとこんな感じ。
intStringAction = (arg0, arg1) =>
{
    Debug.Log("intStringAction");
    Debug.Log(arg0);
    Debug.Log(arg1);
};
もちろん関数を入れてやることもできますよ。
voidAction = () => Start();
さらに、複数登録することもできます。
voidAction = () => Debug.Log("voidAction");
voidAction += () => Debug.Log("voidAction2");
登録した順番で、実行されるみたいですよ。

呼び出し方法

voidAction();
intAction(0);
intStringAction(0, "");
intStringVector3Action(0, "", Vector3.zero);
intStringVector3BehaviourAction(0, "", Vector3.zero, this);
関数のように呼び出せます。
ただこの場合、nullチェックが行われないので、Invokeで呼び出すとチェックを同時に行うことができます。
voidAction?.Invoke();
intAction?.Invoke(0);
intStringAction?.Invoke(0, "");
intStringVector3Action?.Invoke(0, "", Vector3.zero);
intStringVector3BehaviourAction?.Invoke(0, "", Vector3.zero, this);
こんな感じです。


以上でした

0 件のコメント :

コメントを投稿