facebook twitter hatena line email

Unity/Csharp/Delegate

提供: 初心者エンジニアの簡易メモ
2018年11月15日 (木) 02:27時点におけるAdmin (トーク | 投稿記録)による版

移動: 案内検索

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 [ショートカット]