我正在制作一个事件,当它触发时会执行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
并使我的所有其他ienumerator静态但我得到一个名为“非静态字段需要对象引用...”的错误 因此,我尝试了事件的东西。 一切都很好,但是我无法从其他脚本调用该事件,因为我无法从提到的脚本中传递它的功能。 现在做什么?
答案 0 :(得分:1)
以下是示例代码:
<强> 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);
}
}
答案 1 :(得分:1)
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复制,也许协同程序是相同的,然后你需要在void Start() {}
中启动协同程序,你可能会发现this也很有用。