1
\$\begingroup\$

I am trying to replicate the model of Unity documentation about coroutines, but I want to partition it in another class:

I have these two:

public class A: MonoBehaviour {

    void Start() {
        print("Starting " + Time.time);
        B test = new B();
        StartCoroutine(test.WaitAndPrint(2.0F));
        print("Before WaitAndPrint Finishes " + Time.time);
    }
}

public class B: MonoBehaviour {

    public IEnumerator WaitAndPrint(float waitTime) {
        yield return new WaitForSeconds(waitTime);
        print("WaitAndPrint " + Time.time);
    }
}

It prints, ignoring the coroutine:

Starting 0 Before WaitAndPrint Finishes 0

The two methods work well in the same class.

\$\endgroup\$
4
  • \$\begingroup\$ Is TesteWait the same as class B? If not, can you include the code for this class? \$\endgroup\$
    – DMGregory
    Jul 24, 2016 at 1:53
  • \$\begingroup\$ So far I haven't been able to reproduce the problem. Starting a Coroutine in one MonoBehaviour using a public IEnumerator available on another works as expected: the start method runs to completion and then the delayed print occurs after the wait time elapses. Are you deleting or disabling any objects, which might cause the coroutine state to be lost? \$\endgroup\$
    – DMGregory
    Jul 24, 2016 at 2:00
  • \$\begingroup\$ @DMGregory Sorry I renamed classes to A and B for intelligibility, but forgot to rename it in the middle of code. Fixed. \$\endgroup\$
    – JamesB
    Jul 24, 2016 at 14:27
  • \$\begingroup\$ @DMGregory I'm using it attached to one scene object, the instantiation is of a script that is in a asset folder. It's accessible because when I do the with a common method in the be class it works. \$\endgroup\$
    – JamesB
    Jul 24, 2016 at 14:31

1 Answer 1

1
\$\begingroup\$

B test = new B() is not allowed for Components & MonoBehaviours in Unity; there cannot be constructors.

Use something like: test = gameObject.AddComponent<B>();

\$\endgroup\$
7
  • \$\begingroup\$ Despise the warnings, it is working for all the purposes, I want to use scripts without attaching it to any GameObject, direct from assets. \$\endgroup\$
    – JamesB
    Jul 24, 2016 at 14:33
  • \$\begingroup\$ @JamesB then don't make it a MonoBehaviour if you don't intend to use it the way Monobehaviours are used. \$\endgroup\$
    – DMGregory
    Jul 24, 2016 at 14:35
  • \$\begingroup\$ if you want some kind of util class use static and there will be no need to attach that component \$\endgroup\$
    – Yevhen
    Jul 24, 2016 at 14:35
  • \$\begingroup\$ @DMGregory It'depends of class, because some of them I lose SctartCoroutine methods for example. \$\endgroup\$
    – JamesB
    Jul 24, 2016 at 14:40
  • 1
    \$\begingroup\$ gameObject.StartCoroutine(StaticClass.StaticMethod()) will work, FYI @jamesB \$\endgroup\$
    – Yevhen
    Jul 25, 2016 at 18:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .