c#委托和事件和unity应用

本文通过一个Unity示例解释了委托和事件的概念。在Unity中,委托是一种定义方法类型的机制,允许我们将多个方法绑定到同一个事件上。事件则是对委托的封装,常用于响应特定事件的发生,如EditorApplication.playModeStateChanged事件。当编辑器的播放模式状态改变时,该事件会被触发,调用绑定的方法LogPlayModeState,从而打印出当前的PlayMode状态。
摘要由CSDN通过智能技术生成

委托和事件

参考
起因:
在这里插入图片描述
简单理解一下:
什么是委托?定义方法的类型。
在这里插入图片描述
可以将多个方法绑定到委托上 使用+=,同理取消方法的绑定-=
什么是事件?类似属性对字段的封装,是对委托变量的封装
在这里插入图片描述

unity中一个小栗子

using UnityEngine;
using UnityEditor;

// ensure class initializer is called whenever scripts recompile
[InitializeOnLoadAttribute]
public static class PlayModeStateChangedExample
{
    // register an event handler when the class is initialized
    static PlayModeStateChangedExample()
    { 
        
        EditorApplication.playModeStateChanged -= LogPlayModeState;
        EditorApplication.playModeStateChanged += LogPlayModeState;
    }

    private static void LogPlayModeState(PlayModeStateChange state)
    {
        Debug.Log(state);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值