【问题标题】:Unity3d StartCoroutine from another script来自另一个脚本的 Unity3d StartCoroutine
【发布时间】:2014-11-12 23:55:48
【问题描述】:

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

【问题讨论】:

  • 从 ScriptTwo 调用 ScriptOne 中的一个方法来启动协程。使用 GetComponent() 获取对 ScriptOne 组件的引用。

标签: c# unity3d coroutine


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    公共类 ScriptTwo : MonoBehaviour {

    [SerializeField] ScriptOne scriptOne;
    
    void Start() { StartCoroutine(scriptOne.StartSmth()); }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多