且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Unity中的简单事件系统

更新时间:2022-06-20 01:32:16

您必须使用 UnityEvent

    public UnityEvent whoa;

这不容易。使用UnityEngine制作脚本BigScript.cs

It could not be easier. Make a script BigScript.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Events;

public class BigScript:MonoBehaviour
    {
    [Header("Here's a cool event! Drag anything here!")]
    public UnityEvent whoa;
    }

将其放在游戏对象上。现在,在检查器中查看它。好吧?

Put it on a game object. Now look at it in the Inspector. Cool right?

很简单。要在BigScript中调用该事件,它只是

It's that simple. To call the event in BigScript, it is just

public class BigScript:MonoBehaviour
    {
    [Header("Here's a cool event! Drag anything here!")]
    public UnityEvent whoa;

    private void YourFunction()
      {
      whoa.Invoke();
      }

(如果您愿意, if(whoa!= null)whoa.Invoke();

如果你是新的:优秀的Unity Events视频教程

在极少数情况下,您可能需要通过代码添加一个监听器。 (我的意思是,而不是简单地在编辑器中拖动它。)

In rare cases you may need to add a listener via code. (I mean, rather than simply dragging it in the Editor.)

whoa.AddListener(ScreenMaybeChanged);

我只提到它的完整性。

这就是它的所有。

Unity事件是Unity如何令人难以置信的一个惊人的例子。永远记住,如果您正在做一些复杂的工作,那么在使用Unity时,您会错误的做到这一点。这是小孩戏。

Unity Events are an amazing example of how Unity make it ridiculously easy. Always remember that when working with Unity if you're doing something complicated, you're doing it the wrong way. It's child's play.