Unity3D委托的使用

https://blog.csdn.net/u012322710/article/details/52911937

链接中的原文,学习委托的使用,记录一下:

public class MyDelegate : MonoBehaviour
{
    public delegate void LogDelegate(string log);   
    public static LogDelegate LogEvent;            
    public static void OnLogEvent(string log)       
    {
        if (LogEvent != null)
        {
            LogEvent(log);
        }
    }
}

使用:

public class MyInvoke : MonoBehaviour {

    void Start()
    {
        MyDelegate.LogEvent += MyLog;
        MyDelegate.LogEvent += MyLog2;
        MyDelegate.OnLogEvent("给你们这些小函数发回调消息了啊!");
    }

    void MyLog(string log)
    {
        Debug.Log("这种委托方法真是好用的不得了!我收到你的消息了:" + log);
    }
    void MyLog2(string log)
    {
        Debug.Log("可以实现消息触发回调,好方便!我也收到了:" + log);
    }
}

有单个对象调用时很好用,如果场景中有多个MyInvoke类的对象,调用时会重复:

可以添加返回bool的方法判断

bool MethodIsRegistered(string methodName)
    {
        if (MyDelegate.LogEvent == null)
            return false;

        for (int ctr = MyDelegate.LogEvent.GetInvocationList().Length - 1; ctr >= 0; ctr--)
        {
            var outputMsg = MyDelegate.LogEvent.GetInvocationList()[ctr];
            //outputMsg.DynamicInvoke("Greetings and salutations!");
            if (outputMsg.Method.Name == methodName)
            {
                return true;
            }
        }
        return false;
    }

*针对上述出现重复问题,回调的时候会出现,如果不用回调则不会出现重复。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值