简体   繁体   English

如何在 Unity3D 中使用 C# 事件

[英]How to use C# events in Unity3D

I've been working with Events for some time with Winforms, but I'm still quite new with Unity stuff.我使用 Winforms 使用 Events 已经有一段时间了,但我对 Unity 的东西仍然很陌生。 My project is just to get some C# code running on Android so there's no need for a super efficient solution, just a working one.我的项目只是让一些 C# 代码在 Android 上运行,所以不需要超级高效的解决方案,只需要一个有效的解决方案。

Event Handler declaration:事件处理程序声明:

public event EventHandler OnShow, OnHide, OnClose;

Event Handler call:事件处理程序调用:

Debug.Log("OnShow");
if (OnShow != null) 
{
Debug.Log("OnShow_Firing");
OnShow(this, new EventArgs()); 
}
else{
Debug.Log("OnShow_empty");
}

Event Handler Added in an other script but the same gameobject事件处理程序在另一个脚本中添加但相同的游戏对象

void Awake(){
Debug.Log("Awake");
this.gameObject.GetComponent<windowScript>().OnShow += OnShowCalled;
}
private void OnShowCalled(object o,EventArgs e)
{
Debug.Log("OnShowCalled");
}

My Debug output is following:我的调试输出如下:

  1. "Awake" “醒了”
  2. "OnShow" 《在场》
  3. "OnShowFiring" 《在场开火》

but "OnShowCalled" is never executed, there're no Exceptions in Unity's console.但是“OnShowCalled”永远不会执行,Unity 的控制台中没有异常。 I tested EventArgs.Empty instead of new EventArgs() as mentioned in the comments with no effect on my problem .我测试了EventArgs.Empty而不是评论中提到的new EventArgs() ,但对我的问题没有影响。

Looking forward for any help.期待任何帮助。

First of all check this tutorial : https://unity3d.com/learn/tutorials/topics/scripting/events首先检查本教程: https : //unity3d.com/learn/tutorials/topics/scripting/events

I would recommend using event Action .我建议使用event Action It is easier to use for beginners.对于初学者来说更容易使用。

Example :示例:

Class containing events:包含事件的类:

public class EventContainer : MonoBehaviour
{
    public event Action<string> OnShow;
    public event Action<string,float> OnHide;
    public event Action<float> OnClose;

    void Show()
    {
        Debug.Log("Time to fire OnShow event");
        if(OnShow != null)
        {
            OnShow("This string will be received by listener as arg");
        }
    }

    void Hide()
    {
        Debug.Log("Time to fire OnHide event");
        if(OnHide != null)
        {
            OnHide ("This string will be received by listener as arg", Time.time);
        }
    }



    void Close()
    {
        Debug.Log("Time to fire OnClose event");
        if(OnClose!= null)
        {
            OnClose(Time.time); // passing float value.
        }
    }
}

Class which handles events of EventContainer class:处理 EventContainer 类事件的类:

public class Listener : MonoBehaviour
{
    public EventContainer containor; // may assign from inspector


    void Awake()
    {
        containor.OnShow += Containor_OnShow;
        containor.OnHide += Containor_OnHide;
        containor.OnClose += Containor_OnClose;
    }

    void Containor_OnShow (string obj)
    {
        Debug.Log("Args from Show : " + obj);
    }

    void Containor_OnHide (string arg1, float arg2)
    {
        Debug.Log("Args from Hide : " + arg1);
        Debug.Log("Container's Hide called at " + arg2);
    }

    void Containor_OnClose (float obj)
    {
        Debug.Log("Container Closed called at : " + obj);
    }

}

For debugging purposes add a Tag property to your component.出于调试目的,向您的组件添加一个Tag属性。 Then initialize with:然后初始化:

var component = this.gameObject.GetComponent<windowScript>();
component.Tag = "foo";
component.OnShow += OnShowCalled;    

And change the logging并更改日志记录

Debug.Log("OnShow: " + Tag);

and you will see whether you're dealing with the same object.你会看到你是否在处理同一个对象。

Not enough reputation, but possible duplicate or related?没有足够的声誉,但可能重复或相关?

Simple event system in Unity Unity 中的简单事件系统

Events in Unity should be usingUnityEvent . Unity 中的事件应该使用UnityEvent

Standard C# events don't work as expected since Unity executes code in a different way than vanilla C# (I don't know much about the topic, but I'm sure someone else does).标准 C# 事件无法按预期工作,因为 Unity 以与普通 C# 不同的方式执行代码(我对该主题了解不多,但我确定其他人知道)。

In addition, Unity uses an Entity Component System.此外,Unity 使用实体组件系统。 See http://answers.unity3d.com/questions/669643/entity-component-system.html for more information.有关更多信息,请参阅http://answers.unity3d.com/questions/669643/entity-component-system.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM