[英]Unity3d StartCoroutine from another script
我有两个 C# 脚本: ScriptOne
包含IEnumerator StartSmth(){...}
和ScriptTwo
。 如何从ScriptTwo
启动协程StartSmth()
?
这是 LearnCocos2D 答案的更加充实的版本。
我假设您的脚本存在于不同的游戏对象上(如果不是,您可以忽略在下面的代码中引用游戏对象 A)。 您需要执行以下操作:
游戏对象 A 上的 Script1
public class Script1 : MonoBehaviour {
void Start() {}
void Update() {}
public void MethodToCall(){
//Start coroutine here
}
}
游戏对象 B 上的 Script2
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()); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.