Use coroutine inside a non MonoBehaviour class

后端 未结 1 1310
执笔经年
执笔经年 2020-12-02 00:39

How can you pass a Monobehaviour inside an instance of a non Monobehaviour class? I found this link where TonyLi mentions that you can pass a Monobehaviour to start and stop

相关标签:
1条回答
  • 2020-12-02 01:24

    TonyLi mentions that you can pass a Monobehaviour to start and stop coroutines inside a instance of a class, but he does not show how you can do that. He does this

    You are can do that with the this keyword. The this keyword will get the current instance of MonoBehaviour.

    In this example there's a tree, which happens to have a component MonoScript:

    That particular instance of MonoScript can if it wants (since it's a c# program) instantiate a general c# class, NonMonoScript:

    Class to pass MonoBehaviour from:

    public class MonoScript : MonoBehaviour
    {
        void Start()
        {
            NonMonoScript  nonMonoScript = new NonMonoScript();
            //Pass MonoBehaviour to non MonoBehaviour class
            nonMonoScript.monoParser(this);
        }
    }
    

    Class that receives pass MonoBehaviour instance:

    public class NonMonoScript 
    {
        public void monoParser(MonoBehaviour mono)
        {
            //We can now use StartCoroutine from MonoBehaviour in a non MonoBehaviour script
            mono.StartCoroutine(testFunction());
    
           //And also use StopCoroutine function
            mono.StopCoroutine(testFunction());
        }
    
        IEnumerator testFunction()
        {
            yield return new WaitForSeconds(3f);
            Debug.Log("Test!");
        }
    }
    

    You can also store the mono reference from the monoParser function in a local variable to be re-used.

    0 讨论(0)
提交回复
热议问题