【发布时间】:2014-11-12 23:55:48
【问题描述】:
我有两个 C# 脚本:
ScriptOne 包含 IEnumerator StartSmth(){...} 和 ScriptTwo。如何从ScriptTwo 启动协程StartSmth()?
【问题讨论】:
-
从 ScriptTwo 调用 ScriptOne 中的一个方法来启动协程。使用 GetComponent
() 获取对 ScriptOne 组件的引用。
我有两个 C# 脚本:
ScriptOne 包含 IEnumerator StartSmth(){...} 和 ScriptTwo。如何从ScriptTwo 启动协程StartSmth()?
【问题讨论】:
这是 LearnCocos2D 答案的更充实的版本。
我假设您的脚本存在于不同的游戏对象上(如果不是,您可以忽略在下面的代码中引用游戏对象 A)。您需要执行以下操作:
游戏对象 A 上的脚本 1
public class Script1 : MonoBehaviour {
void Start() {}
void Update() {}
public void MethodToCall(){
//Start coroutine here
}
}
游戏对象 B 上的脚本 2
public class Script2 : MonoBehaviour{
public GameObject gameObjA; //reference to the game object the other script lives on. (this can also be done dynamically)
void Start(){
//logic to call target method on Script1
var script1 = gameObjA.GetComponent<Script1>();
script1.MethodToCall();
}
void Update() {}
}
【讨论】:
我知道这篇文章很旧,但它仍然会出现在我的 Google 搜索中。生活在不同游戏对象上的协程可以很容易地启动。
公共类 ScriptTwo : MonoBehaviour {
[SerializeField] ScriptOne scriptOne;
void Start() { StartCoroutine(scriptOne.StartSmth()); }
}
【讨论】: