创建从另一个脚本触发协程的事件

Create events that fires off a coroutine from another script

我正在制作一个事件,它在触发时执行 failLevel 操作。为此,我做了一个代表

    public delegate Coroutine FailGame(IEnumerator function);
    public static event FailGame gameFailedEvent;

像这样,我订阅了相应的功能

void Start ()
    {
        gameFailedEvent += StartCoroutine;
    }

当它从同一个脚本调用时有效,如下所示:

gameFailedEvent(WaitThenFailLevel());

当这个 WaitThenFailLevel() 看起来像这样时:

IEnumerator WaitThenFailLevel()
    {
        CharacterController2D.playerDied = true;
        if (CharacterController2D.animState != CharacterController2D.CharAnimStates.fall)
        {
            CharacterController2D.currentImageIndex = 0;
            CharacterController2D.animState = CharacterController2D.CharAnimStates.fall;
        }
        CharacterController2D.movementDisabled = true;
        yield return new WaitForSeconds(0.2f);
        StartCoroutine(ScaleTime(1.0f, 0.0f, 1.2f));
    }

在这里工作正常。现在,我有另一个可以杀死玩家的对象(我知道这是危险的时刻),我不想再次复制粘贴所有内容,我只想让它触发上面脚本中生成的静态事件。

我确实尝试制作 WaitThenFailGame 函数

public static

并将我所有其他的 ienumerators 设置为静态,但我收到一个名为 "An object reference is required for non-static field..." 的错误 因此我尝试了事件的东西。 一切都很好,但我无法从其他脚本调用事件,因为我无法将上述脚本中的函数传递给它。 现在要做什么?

示例代码如下:

EventContainor.cs

public class EventContainer : MonoBehaviour
{
    public static event Action<string> OnGameFailedEvent;

    void Update()
    {
        if (Input.GetKey(KeyCode.R))
        {
            // fire the game failed event when user press R.
            if(OnGameFailedEvent = null)
                OnGameFailedEvent("some value");
        }

    }
}

Listener.cs

public class Listener : MonoBehaviour
{

    void Awake()
    {
        EventContainer.OnGameFailedEvent += EventContainer_OnGameFailedEvent;
    }

    void EventContainer_OnGameFailedEvent (string value)
    {
        StartCoroutine(MyCoroutine(value));
    }

    IEnumerator MyCoroutine(string someParam)
    {
        yield return new WaitForSeconds(5);

        Debug.Log(someParam);
    }

}
using UnityEngine;
public class ScriptA : MonoBehaviour
{
  public ScriptB anyName;


  void Update()
  {
    anyName.DoSomething();
  }
}

using UnityEngine;
public class ScriptB : MonoBehaviour
{
  public void DoSomething()
  {
     Debug.Log("Hi there");
  }
}

这是脚本之间的链接函数,从 Here, maybe coroutines are the same, Then you need to start the coroutine in void Start() {} , You may find this 复制而来也很有用。