facebook twitter hatena line email

「Unity/Csharp/Delegate」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
行16: 行16:
 
     {
 
     {
 
         Success,
 
         Success,
         Faild,
+
         Failure,
 
         NetworkError
 
         NetworkError
 
     }
 
     }
行38: 行38:
 
             if (callbacks != null)
 
             if (callbacks != null)
 
             {
 
             {
                 callbacks(ResponseType.Faild);
+
                 callbacks(ResponseType.Failure);
 
             }
 
             }
 
         }
 
         }
行70: 行70:
 
                 Debug.Log("msg=" + mountain.GetMessage());
 
                 Debug.Log("msg=" + mountain.GetMessage());
 
             }
 
             }
             else if (responseType.Equals(mountain.ResponseType.Faild))
+
             else if (responseType.Equals(mountain.ResponseType.Failure))
 
             {
 
             {
 
                 Debug.Log("msg=" + mountain.GetMessage());
 
                 Debug.Log("msg=" + mountain.GetMessage());

2018年11月15日 (木) 02:27時点における版

delegateとは

独自イベントを生成できるもの。httpのレスポンスなど少し待たないとレスポンスが戻ってこないところで使う。

delegateのサンプル

"やっほー"をリクエストすると1/2の確率で"やっほー"を返してくれるサンプル

delegateを宣言

  • Mountain.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mountain : MonoBehaviour {
    private string msg;
    public enum ResponseType
    {
        Success,
        Failure,
        NetworkError
    }
    public delegate void CustomCallback(ResponseType responseType);
    private CustomCallback callbacks;
    public void AddCallback(CustomCallback callback)
    {
        callbacks += callback;
    }
    public void Exec(string msg)
    {
        // 1/2の確率で成功
        if (Random.Range(-10.0f, 10.0f) > 0) {
            this.msg = msg;
            if (callbacks != null)
            {
                callbacks(ResponseType.Success);
            }
        } else {
            this.msg = "";
            if (callbacks != null)
            {
                callbacks(ResponseType.Failure);
            }
        }
    }
    public string GetMessage() {
        return msg;
    }
}

呼び出し元

  • NewBehaviourScript.cs
public class NewBehaviourScript : MonoBehaviour {
    Mountain mountain;
    // 送信
    void Start () {
        GameObject gameObj = new GameObject();
        mountain = gameObj.AddComponent<Mountain>();
        mountain.AddCallback(OnResponse);
        mountain.Exec("やっほー");
    }
    // 受信
    public void OnResponse(Mountain.ResponseType responseType)
    {
        Debug.Log("OnResponse=" + responseType);
        if (mountain)
        {
            if (responseType.Equals(mountain.ResponseType.Success))
            {
                Debug.Log("msg=" + mountain.GetMessage());
            }
            else if (responseType.Equals(mountain.ResponseType.Failure))
            {
                Debug.Log("msg=" + mountain.GetMessage());
            }
        }
    }
}

httpでdelegateを使った例

unity/Csharp/Request [ショートカット]