這幾天因為要弄這個任務系統,接觸C#的委託與事件,剛開始看的時候頭真的是很大,找了很多說明的,都是越看越是糊塗,最後看到一篇文章才漸漸有點靈感。感謝
http://www.cnblogs.com/David-Huang/p/5150671.html 此部落格博主。
委託:個人在這裡理解 委託就是 定義一個引用,一個可以記錄函式指標的引用。
public delegate void GreetingDelegate(int param);
事件:就是基於委託定義的。
public event GreetingDelegate payxx;
其實這裡的事件 payxx 就差不多和string 一樣可,只不過是存函式指標的變數。
這裡上一個例子程式碼:
using UnityEngine; using System.Collections; using UnityEngine.UI; using System; public class basetest : MonoBehaviour { public GameObject panel; private bool isclick = false; public delegate void GreetingDelegate(int param); public event GreetingDelegate payxx; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } void OnMouseOver() { if (Input.GetMouseButtonDown(0)) { //左鍵點選 Debug.LogError("你點選了NPC"); //playRenwu(); } } public void pay() { Debug.LogError("觸發了委託"); } void playRenwu(bool isnotclick) { Debug.LogError("開始NPC任務"); panel.gameObject.SetActive(isnotclick); } //protected virtual void Onpayxxxxx(int param) //{ // if (payxx != null) // { // Debug.LogError("委託的事件觸發了"); // payxx(param); // } // else // { // Debug.LogError("委託的事件沒觸發"); // } //} public void Onpayxx(int param) { if (payxx != null) { payxx(param); } else { } } public void Myfuntion2(int param) { Debug.LogError("第二次呼叫=" + param); } public void MyFunction(int param) { Debug.LogError("OKOKOKOKO=" + param); } public void Onclickbutton() { basetest eventTest = new basetest(); eventTest.payxx += new GreetingDelegate(MyFunction);//安裝事件 eventTest.payxx += new GreetingDelegate(Myfuntion2);//安裝事件 eventTest.Onpayxx(10); if (isclick == false) { Debug.LogError("你點選了按鈕"); isclick = true; playRenwu(true); } else { isclick = false; playRenwu(false); } } }
payxx 存函式的地址,呼叫是按次數來的。
這裡輸出的結果是: