来自另一个脚本的Unity3d StartCoroutine

时间:2014-09-18 14:58:24

标签: c# unity3d coroutine

我有两个C#脚本: ScriptOne包含IEnumerator StartSmth(){...}ScriptTwo。如何从StartSmth()启动协程ScriptTwo

2 个答案:

答案 0 :(得分:1)

以下是LearnCocos2D答案的更加充实版本。

我假设您的脚本存在于不同的游戏对象上(如果不是,您可以忽略在下面的代码中引用游戏对象A)。您需要执行以下操作:

GameObject A上的Script1

public class Script1 : MonoBehaviour {

    void Start() {}
    void Update() {}

    public void MethodToCall(){
        //Start coroutine here
    }
}

GameObject 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() {}
}

答案 1 :(得分:1)

我知道这篇文章很旧,但它仍然会出现在我的 Google 搜索中。位于不同游戏对象上的协程可以很容易地启动。

公共类 ScriptTwo : MonoBehaviour {

[SerializeField] ScriptOne scriptOne;

void Start() { StartCoroutine(scriptOne.StartSmth()); }

}