Unity3D Delegate

Unity3d 的 Delegate使用方法

1.在Delegate 文件

using UnityEngine;

using System.Collections;

//定義Delegate

public delegate void TestDelegate(int a);

public class DelegateScripts : MonoBehaviour {
   
//使用

public event TestDelegate testDelegate;
    public void DoSomeThing() {;
       
//調用 testDelegate 作爲回調方法

testDelegate(111);
    }
    public void TestTwoDemo()
    {
        print("TestTwo22");
    }
    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
}
}
   

2.在調用Delegate文件裏面

    private DelegateScripts delegateScripts;

 void Start () {
        int a = 3;


        delegateScripts = GameObject.FindObjectOfType<DelegateScripts>();
       //定義delegate  作爲回調 方法 (callBack)

 delegateScripts.testDelegate += new TestDelegate(callBack);
       //調用delegateScripts的DoSomeThing 方法,回調方法是CallBack

 delegateScripts.DoSomeThing();
    }


    private void callBack( int aa )
    {
        print(" aa = " + aa);
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章