Unity3d实现C# Event的基本实例

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载,博客地址:http://blog.csdn.net/xpala https://blog.csdn.net/xpala/article/details/89376702

现有一个事件Button, 事件Button的委托为ButtonHandler,该委托只接受参数类型为string,返回值为void的方法

处理事件的方法有两个:DownMethod和UpMethod,    在程序中订阅DownMethod,在Update()中触发事件

代码如下

public class ButtonEvent : MonoBehaviour
{
    //定义了委托 ,参数类型string,返回值为void
    public delegate void ButtonHandler(string buttonName);

    //定义委托的事件
    public static event ButtonHandler Button;

    void Start()
    {
        //开始DownMethod1就订阅了事件ButtonDown
        ButtonEvent.Button += DownMethod;
    }

    // Update is called once per frame
    void Update()
    {
        if(Button!=null)
        {
            //由于订阅了事件,每帧都会使用DownMethod去处理事件
            Button("This is Downkey");
        }
    }

    //处理事件的方法1:DownMethod
    void DownMethod(string btnName)
    {
        print(btnName+"Down!");
    }
    //处理事件的方法2:UpMethod
    void UpMethod(string btnName)
    {
        print(btnName + "Up!");
    }
}

在Unity3d中运行结果如下:

每帧都触发了事件和处理了订阅事件的方法

猜你喜欢

转载自blog.csdn.net/xpala/article/details/89376702