Concurrent Coroutine Question

Hello!

I have a concurrent function that takes a lot of memory in my game, I am working on some start evaluation and I got a code that is really expensive in processing power.

I read about using coroutines, but I am not sure on how to do it on these kinds of fucntions

please help

//C#

protected void DoSomeFoo() { ... while(condition){ DoSomeFoo(); } ... }

This illustrates the general idea of how optimisation works in the Path project:

delegate void OnPathCompletedDelegate ();

public void CalculatePath (float maxFrameTime, OnPathCompletedDelegate callback)
{
    StartCoroutine (UpdatePath (maxFrameTime, callback));
}

private IEnumerator UpdatePath (float maxFrameTime, OnPathCompletedDelegate callback)
{
    do
    {
    	float frameStart = Time.realtimeSinceStartup;

    	while (Time.realtimeSinceStartup - frameStart < maxFrameTime)
    	{
    		if (IteratePath ())
    		{
    			callback ();
    			yield break;
    		}
    	}

    	yield return null;
    }
    while (Application.isPlaying);
}

The way it works is you specify the maximum duration of a Path solver frame in order to not limit the solver to only run one iteration per frame, while at the same time not hanging the game to solve the whole thing in one frame.

To get the best performance, use

yield return null;

this is much, much faster. there is a blog post here. if your function doesen't need to be executed every frame you can yield it for 1 second or 0.1 second by

yield return new WaitForSecond (0.1f);

You would convert it to something like this. I'm assuming that you didn't mean for your example to be recursive, and the 2nd "DoSomeFoo" function should be some other function.

protected void DoSomeFoo()
{
    StartCoroutine(FooCoroutine());
    // returns immediately;
}

protected IEnumerator FooCoroutine()
{
    while(condition)
    {
        DoSomeSubsetOfExpensiveFunction();
        yield return 0;
    }
}

I am sorry, I am not explaining myself well. The method needs to call itself recurrently in order for my code to work. However, this turns out to be heavy for Unity. Here's the edited code to be more clear

protected void DoSomeFoo(Node node) 
{ 
   ... 
   foreach(Node childNode in Node.Children)
   { 
      DoSomeFoo(childNode); 
   } ... 
}

NOTE: Node is a class I created.

thanks.