「Unity/Csharp/コールバック」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==実装例== Unity/Csharp/Request [ショートカット]」) |
|||
(同じ利用者による、間の2版が非表示) | |||
行1: | 行1: | ||
+ | ==サンプル== | ||
+ | <pre> | ||
+ | public class SampleManager : MonoBehaviour | ||
+ | { | ||
+ | private static SampleManager mInstance; | ||
+ | private SampleManager() | ||
+ | { | ||
+ | } | ||
+ | public static SampleManager Instance | ||
+ | { | ||
+ | get | ||
+ | { | ||
+ | if (mInstance == null) mInstance = new SampleManager(); | ||
+ | return mInstance; | ||
+ | } | ||
+ | } | ||
+ | public enum ResponseType | ||
+ | { | ||
+ | CommentAdded, | ||
+ | } | ||
+ | public delegate void CustomCallback(ResponseType responseType, string comment); | ||
+ | private CustomCallback callbacks; | ||
+ | public void AddCallback(CustomCallback callback) | ||
+ | { | ||
+ | callbacks += callback; | ||
+ | } | ||
+ | public void CommentAdded() | ||
+ | { | ||
+ | // 色々処理 | ||
+ | if (callbacks != null) | ||
+ | { | ||
+ | callbacks(ResponseType.CommentAdded, "comment!!"); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | Main.cs | ||
+ | <pre> | ||
+ | void Start() | ||
+ | { | ||
+ | manager = SampleManager.Instance; | ||
+ | manager.AddCallback(OnResponse); | ||
+ | manager.CommentAdded(); | ||
+ | } | ||
+ | void OnResponse(SampleManager.ResponseType responseType, string comment) | ||
+ | { | ||
+ | Debug.Log("OnResponse=" + responseType + " comment=" + comment); | ||
+ | } | ||
+ | </pre> | ||
==実装例== | ==実装例== | ||
[[Unity/Csharp/Request]] [ショートカット] | [[Unity/Csharp/Request]] [ショートカット] |
2021年11月11日 (木) 04:44時点における最新版
サンプル
public class SampleManager : MonoBehaviour { private static SampleManager mInstance; private SampleManager() { } public static SampleManager Instance { get { if (mInstance == null) mInstance = new SampleManager(); return mInstance; } } public enum ResponseType { CommentAdded, } public delegate void CustomCallback(ResponseType responseType, string comment); private CustomCallback callbacks; public void AddCallback(CustomCallback callback) { callbacks += callback; } public void CommentAdded() { // 色々処理 if (callbacks != null) { callbacks(ResponseType.CommentAdded, "comment!!"); } } }
Main.cs
void Start() { manager = SampleManager.Instance; manager.AddCallback(OnResponse); manager.CommentAdded(); } void OnResponse(SampleManager.ResponseType responseType, string comment) { Debug.Log("OnResponse=" + responseType + " comment=" + comment); }
実装例
Unity/Csharp/Request [ショートカット]