I have two classes, ClassA and ClassB.
In Class B there is this method (cA is a reference to class A):
In Class A is the do stuff method:
Both times come out the same, even though they should be two seconds apart. Both classes are Monobehaviours and the contents of the methods work fine. They do their job, its just that it takes awhile and I would like to keep the rest of the game updating. But currently it seems the yields are just ignored, what gives?
DoStuff needed to be started from a method in it's own script. A dummy middleman solved that. The real problem arose when I did that. The equivalent DoStuff() in my script is called around 100 times within the same frame. This freezes the game as if you didn't even have the yield in there. Thus all the DoStuffs() have the same start and end time because they are running parallel to each other.
I could fix this with a 'yield return StartCoroutine' but this would require the middleman to be of type IEnumerator, which would bring me back to my original problem of not being able to call the method from another script.
So in order to yield you need IEnumerator and to call the method with the yield you need an IEnumerator, then to call that method... so on and so on.
How do you break this endless chain of Enumerators?
I found a workaround which does not use yield.
Still, here's a (hopefully) more specific explanation of what I am doing: There are two classes, one that generates the locations for hundreds of GameObjects and stores them in an array in the other class.
Class A is the Generator
Class B is the Renderer and handles all displaying/retrieving/manipulating of the GameObjects
Before the first update is ever called, The Generator (A) goes to work placing references to all these GameObjects and Renderer (B) begins Instantiate what the Generator says to make. This takes a long time and freezes the game during the process.
If I threw a yield every time the Renderer finished a task (each one taking around 0.2 seconds processing time), the game would not freeze. That's the situation.
I can put a yield in but the resulting Coroutine code causes there to be so many Coroutines running that it might as well not have any yields.
My workaround is fairly simple: The Generator adds the GameObjects to be Instantiated to a queue and then the Renderer makes a bunch every time Update is called.
There may not be a clean answer to this problem. I'm sorry if it's a bit hard to understand what I wrote.
If I run those scripts (replacing "Entrance" with "Start" and creating an appropriate cA variable for the first script), then the output is:
So in fact everything works as expected.
answered Sep 01 '11 at 05:15 AM
There could be an issue with starting a coroutine in a different script. If so, can work-around by converting DoStuff into a "driver":
answered Sep 01 '11 at 07:38 AM