Simple understanding and implementation of Unity delegate (Delegate)

Delegation is equivalent to treating a certain method as a parameter. When executing the delegate, it is equivalent to executing the method, so this method must have the same parameter type as the delegate.

Simple implementation of delegation


using UnityEngine;

//委托(代理) 是存有对某个方法的引用的一种引用类型变量。
//委托语法:delegate <return type> <delegate-name> <parameter list>
public class DelegateTest : MonoBehaviour
{
    //声明一个没有返回值的委托,委托可以写在类中也可以写在类名的外面
    public delegate void PrintString(string value);
    
    void Start()
    {
        DebugString("普通的方法");

        //声明一个委托并且将和委托具有相同参数类型的方法DebugString传入
        PrintString p1 = new PrintString(DebugString);
        //此时这个委托具有和 DebugString方法相同的功能
        p1("委托测试");
    }
    //普通的方法,输出你传入的字符串
    public void DebugString(string s)
    {
        Debug.Log(s);
    }
  
}

 Output results


Multicast: Delegate objects can be combined using the "+" operator. A merged delegate calls the two delegates it merges. Only delegates of the same type can be merged. The "-" operator can be used to remove component delegates from merged delegates.

To put it simply, multiple methods can be executed during delegate execution.


using UnityEngine;

//多播(组播),委托对象可使用 "+" 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。"-" 运算符可用于从合并的委托中移除组件委托。
public class DelegateTest : MonoBehaviour
{
    //声明一个没有返回值的委托,委托可以写在类中也可以写在类名的外面
    public delegate void PrintString(string value);
    
    void Start()
    {

        //声明一个委托并且将和委托具有相同参数类型的方法DebugString传入
        PrintString p ;
        PrintString p1 = new PrintString(DebugStringOne);
        PrintString p2 = new PrintString(DebugStringTwo);
       
        p = p1;
        p += p2;
        //调用多播
        p("委托测试");
      
    }
    //普通的方法,输出你传入的字符串
    public void DebugStringOne(string s)
    {
        Debug.Log("DebugStringOne:" + s);
    }
    public void DebugStringTwo(string s)
    {
        Debug.Log("DebugStringTwo:" + s);
    }
}

Output results


 

Guess you like

Origin blog.csdn.net/qq_36592993/article/details/125843149