Unity3D C#检查事件是否为空 [英] Unity3D c# check if event is null

查看:713
本文介绍了Unity3D C#检查事件是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,DelegateHandler是我发送事件的地方

For example, DelegateHandler is where I sent event

public class DelegateHandler : MonoBehaviour
{

     public delegate void OnButtonClickDelegate ();
     public static OnButtonClickDelegate buttonClickDelegate;

     public void OnButtonClick()
     {
     if(buttonClickDelegate!=null)
       buttonClickDelegate ();
     }

}

提到一些线程,我需要先为事件分配一个变量,然后再检查它是否为空,如:

Some thread mentioned I need to assign a variable to the event before checking if it is null like :

    OnButtonClickDelegate tempEvent = buttonClickDelegate;
    if(tempEvent!=null)
       tempEvent();

这是因为,在多线程程序中,我们需要在检查它是否为null和调用事件之间检查是否有一些事件从该事件中取消订阅. 但是Unity3D是单线程的,我们还需要这样做吗?我可以写成

This is because, in multi-thread program, we need to check if some is unsubscribed from the event between checking it is null and invoking event. But Unity3D is single-threaded, do we also need to do this? Can I just write as

     if(buttonClickDelegate!=null)
       buttonClickDelegate ();

推荐答案

提到一些线程,我需要在事件之前分配一个变量 检查它是否为空,如... 但是Unity3D是单线程的,我们还需要这样做吗?

Some thread mentioned I need to assign a variable to the event before checking if it is null like... But Unity3D is single-threaded, do we also need to do this?

否.

您无需在普通的Unity应用中执行此操作.

You don't need to do that in a normal Unity app.

现在,如果您启动另一个Thread,并且想要从该Thread调用该事件,那么必须这样做.如果您创建另一个线程,则不需要这样做.

Now, if you start another Thread and you want to invoke that event from that Thread then yes, you do have to. If you are not creating another Thread, you don't need to do that.

请注意,Unity的回调函数,例如 OnAudioFilterRead 在另一个函数中被调用线.如果您正在使用此功能,并且想要从那里调用事件,那么必须在检查事件是否为null之前为该事件分配一个变量.

Note that Unity's callback function such as OnAudioFilterRead is called in another Thread. If you are using this function and you want to invoke your event from there then you must assign a variable to the event before checking if it is null.

但是我仍然需要检查null,对吗?

But I still need to check null, right?

是的,在调用事件之前,您应该始终检查null.

Yes, you should always check for null before calling an event.

在新的 C#6 中,您可以这样做

In the new C# 6 you could do this

buttonClickDelegate?.Invoke();

删除了null检查,但由于Unity不支持 C#6 ,因此您还不能在Unity中执行此操作.

which removes the null check but you can't do that yet in Unity since Unity does not support C# 6.

这篇关于Unity3D C#检查事件是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆