How To Let Function Run Over Multiple Frames?

I’ve always wondered about this, is it possible? I’m busy programming one dimensional Cellular Automata and I use a function to calculate each cells value on that row, obviously the more cells on the row the more the frame rate drops. So is it possible to let that function or even better the whole script calculate / run over multiple frames so that the frame rate can remain constant.

If you design your function appropriately, this is absolutely possible e.g. by using coroutines:
http://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines?playlist=17117

1 Like

Thanks I just watched a video suggestion from that link and the guy used:
yield return null;
in a while loop I’ve only got a for loop in that function so when I use that it terminates the loop, how would I do it? ( I’m not completely new to coroutines although I’ve mostly only used them for WaitForSeconds() )

Really? It shouldn’t terminate any loop.

Could you show the loop?

Here’s what I’ve done:

// Called like this
StartCoroutine(RuleSet90());
IEnumerator RuleSet90()
{
for (int i = 1; i < resolution - 1; i++)
{
// My Code
yield return null;
}
}

I can only assume that it just does one iteration, i don’t know why.

You can always put a “Debug.Log” in your loop to see how many times it runs.

Nevermind, I just tested with Debug.Log(i); and it is running the loop but i is not incrementing normally it’s something like 1, 2, 1, 3, 2, 4 really strange also it should go all the way up to 256 before going back to 0.

Can you please post your exact code?

here is the code;

IEnumerator Iterate()
{
// non related code
if (RuleSet == “Rule90”)
{
StartCoroutine(RuleSet90());
}
}

IEnumerator RuleSet90()
{
for (int i = 1; i < resolution - 1; i++)
{
if (previous[i - 1] && previous && previous[i + 1])
{
current = false;
continue;
}
// multiple if statements like this just with different values
yield return null;
}
}

That looks like you’re running several instances of the coroutine, each printing their current iterator variable.

1 Like

Thanks everybody, finally worked it out it was being called before the coroutine was complete leading to these weird problems.