简体   繁体   English

Unity中的C#事件

[英]C# Events in Unity

I have two scripts attached to two different game objects, and in one of them I have an Action like this: 我有两个脚本附加到两个不同的游戏对象上,在其中一个脚本中,我有一个如下所示的Action

public class EnemeyController : MonoBehavior
{
    internal Action EnemyWaveKilled;

    private void OnTriggerEnter2D(Collider2D other)
    {
        // If hit by a bullet, kill and raise the event
        EnemyWaveKilled?.Invoke();
    }
}

In my other script's Start method, I try to subscribe to this event in this way: 在其他脚本的Start方法中,我尝试以这种方式预订此事件:

public class GameController : MonoBehavior
{
    internal int PlayerLevel;

    private void Start()
    {
        _enemyController = GameObject.FindWithTag("Enemy").GetComponent<EnemyController>();
        _enemyController.EnemyWaveKilled += () => PlayerLevel++;
    }
}

I have 3 game objects all with tag Enemy in the scene. 我在场景中有3个带有标签Enemy游戏对象。

Now, it seems that my GameController somehow randomly subscribes to the event. 现在,似乎我的GameController以某种方式随机订阅了该事件。

To be more accurate, if I print EnemyWaveKilled.Target in my EnemyController class's Update() method, it displays one line saying it's GameController and two lines saying it's null ) 更准确地说,如果我在EnemyController类的Update()方法中打印EnemyWaveKilled.Target ,它会显示一行表示GameController而显示两行则表示null

Any help is much appreciated 任何帮助深表感谢

I think I know what's happening. 我想我知道发生了什么事。 I have 3 objects with the same tag, but I'm only subscribing to one of them; 我有3个具有相同标签的对象,但是我只订阅其中的一个。 that's why I see the two null values (and a single non- null value) 这就是为什么我看到两个null值(和一个非null值)的原因

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

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