「Unity/Csharp/Action」の版間の差分
提供: 初心者エンジニアの簡易メモ
行2: | 行2: | ||
関数を変数にできるもの | 関数を変数にできるもの | ||
− | == | + | ==Actionサンプル1== |
<pre> | <pre> | ||
System.Action<string> OnMsg = delegate (string msg) { }; | System.Action<string> OnMsg = delegate (string msg) { }; | ||
行12: | 行12: | ||
</pre> | </pre> | ||
− | == | + | ==Actionサンプル2(別クラス呼び出し)== |
<pre> | <pre> | ||
public class ActionScene : MonoBehaviour | public class ActionScene : MonoBehaviour | ||
行41: | 行41: | ||
</pre> | </pre> | ||
+ | |||
+ | ==Actionサンプル3引数で渡して戻す== | ||
+ | <pre> | ||
+ | public class ActionScene : MonoBehaviour | ||
+ | { | ||
+ | void Start() | ||
+ | { | ||
+ | System.Action<string> event = (name) => | ||
+ | { | ||
+ | Debug.Log(name); // hogeが返ってくる | ||
+ | }; | ||
+ | (new sampleLogic).Load(event); | ||
+ | } | ||
+ | } | ||
+ | public class SampleLogic | ||
+ | { | ||
+ | public void Load(System.Action<string> event) | ||
+ | { | ||
+ | event("hoge"); | ||
+ | } | ||
+ | } |
2024年11月13日 (水) 03:44時点における版
Actionとは
関数を変数にできるもの
Actionサンプル1
System.Action<string> OnMsg = delegate (string msg) { }; OnMsg += (msg) => { Debug.Log("msg1:" + msg); }; OnMsg("hello");
Actionサンプル2(別クラス呼び出し)
public class ActionScene : MonoBehaviour { void Start() { var eventActionClass = new EventActionClass(); eventActionClass.Setup( callOnAction: () => { Debug.Log("callOnAction"); }, callOffAction: () => { Debug.Log("callOffAction"); }); } } public class EventActionClass { public void Setup(System.Action callOnAction, System.Action callOffAction) { callOnAction(); callOffAction(); } }
Actionサンプル3引数で渡して戻す
public class ActionScene : MonoBehaviour { void Start() { System.Action<string> event = (name) => { Debug.Log(name); // hogeが返ってくる }; (new sampleLogic).Load(event); } } public class SampleLogic { public void Load(System.Action<string> event) { event("hoge"); } }