跳到主要內容

[C# 筆記] Delegate委派 in unity


表示委派,它是參考到靜態方法或該類別的類別執行個體和執行個體方法 (Instance Method) 的資料結構。
-MSDN的定義



簡言之,就是將方法利用變數的形式去使用之,就像是function pointer,他可以幫你指向你需要的方法,使用上更加的彈性。

最簡單使用delegate有幾個步驟 :

  1. 宣告委派方法之型別(包含返回型態、參數)
  2. 建立一個委派類別實體
  3. 建立相同型別之方法(包含返回型態、參數)
  4. 將欲使用之方法存入委派實體
  5. 透過委派實體使用該方法

範例 1 :

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using UnityEngine;

public class Delegate : MonoBehaviour
{
    delegate void delegatefunction(int num,int num2);

    delegatefunction delegateFunction;

    // Start is called before the first frame update
    void Start()
    {
            delegateFunction = Add;


        if (delegateFunction !=null)
        {
            delegateFunction(2,3);
        }
  

    }

    void Add(int num,int num2)
    {
        print(num+num2);
    }

    
}

輸出 :












第6行: delegate void delegatefunction(int num,int num2);

宣告委派的型別,delegate關鍵字+方法回傳型態  + 委派名稱 + (自訂參數),格式需與欲呼叫之方法相同。

第8行 delegatefunction delegateFunction;實體化委派類別

第13行 將方法傳入委派實體

第18行 delegateFunction(2,3);  執行委派


範例 2 :


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using UnityEngine;

public class Delegate : MonoBehaviour
{
    delegate void delegatefunction(int num,int num2);

    delegatefunction delegateFunction;

    // Start is called before the first frame update
    void Start()
    {
            delegateFunction += Add;
            delegateFunction += Minus;

        if (delegateFunction !=null)
        {
            delegateFunction(2,3);
        }
  

    }

    void Add(int num,int num2)
    {
        print(num+num2);
    }
    void Minus(int num, int num2)
    {
        print(num - num2);
    }

}

輸出 :








第12 13 行 透過+=運算子新增方法

第27行 新增一個Minus方法


留言