while() preventing run?

Hi there,
I have decided to use a while() call to move a background via Translate, however, this code, prevents the game from running. No errors occur, it is just with this code, Unity does not run the game, ir more precisely, tries infinitely to run it, but never does. Removal of this method and it works no problem.

What is going on here?

function MoveGrounds()
{
	while(groundIsActive)
	{
		parentTransform.Translate(Vector3(pathVector.x * Time.deltaTime * groundsSpeed, pathVector.y * Time.deltaTime * groundsSpeed, 0));
	}
	
}

Never use a while loop to make a translation, use the update function, you need to integrate moving objects into the game loop.
What you have is the classic infinite loop mistake, one that the compiler doesn’t detect.

Hm.
Ok, I was hoping to relieve myself of any Updates. It is small, but I have a dozen background objects. Each, running an update, to translate transform. Not all at once. Only 3 or so at a time. My hope was this (using while) would eliminate Updates even going into themselves and checking if condition is true.

Does this make sense? Am I saving much memory? Every bit counts. Is there some type of breaker, condition I can pop in to allow the use of while()?

You can do a coroutine, but coroutines generates lot of garbage.

I think Update() is ok.
If you can and are worried about multiple Update() calls, create a manager that will have the Update function that loop to do your work. But personnaly I think it’s a loss of time for no gain.

Ok,
So, I am wondering, why does this code work, and not mine?

function addTransformToSpline()
{
	// Make the cube "ride" the spline at a constant speed
	do {
		for (var dist = 0.0; dist < 1.0; dist += Time.deltaTime*speed) {
			var splinePoint = splineLine.GetPoint01 (dist);
			cube.position = Camera.main.ScreenToWorldPoint (Vector3(splinePoint.x, splinePoint.y, 10.0));
			loop = false;
			yield;
		}
	} while (loop);		
}

yield instruct unity to return the function, and take it back at the yield position on next call.

If you zhere using C#, the syntax will be more self explanatory:

So it work because the function return at the yield, then unity do his stuff and then call this function again at the next frame.

Edit:
some more info:
http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html

Really? I tend to use Coroutines quite a lot and they often increase performance compared to Update. But I haven’t profiled memory that much…

Yes, ! Ok, so, I was placing the yield outside of the method. It works with the method inside. I am going to stick with this methid, as I say, it will save me running several updates, even tho, most would be returned instantly in enter.

function MoveGrounds()
{
///WORKS!
	while(groundIsActive)
	{
		parentTransform.Translate(Vector3(pathVector.x * Time.deltaTime * groundsSpeed, pathVector.y * Time.deltaTime * groundsSpeed, 0));
		yield;
	}
	
}

@Rasmus, as far as coroutines generating a lot of garbage, I am not sure, but I can say, if you coroutine runs at a tenth of the rate of Update, it it would presumably, produce less garbage. I think, and from what others have said on these boards, that they are still very powerful and useful. I am using until further notice.

:stuck_out_tongue:

To talk about garbage, a coroutine generate one new object every time it start to wait, and this object has to be collected after the wait ended.

If you wait only one frame each time, then use Update because unity will do the while loop for you.
If waiting more than a frame, then maybe it’s better than a direct return in Update because you save the call overhead (but you create a little GC overhead)

So to conclude:
The more frame you wait with a coroutine, the less GC pressure you create, and the less number of instructions you execute per frame.
But if you wait only one frame (or two), you just create more GC pressure without reducing number of instructions per frame.

edit: to adjust a little: there are some case where using coroutine is unavoidable. So don’t worry about GC for thoses special cases because there is almost no other choice.

Have you actually benchmarked or tested any of what you’re saying?

Coroutines have some GC overhead because they create an Enumerator that needs to be disposed of when the Coroutine ends - however to say that they execute fewer instructions per frame is misleading. You’re still processing the Coroutine every frame you simply save the invocation of an Update method. Also note that you’re not “generating a new object every frame” in nearly all cases (you’re simply returning null as part of the Enumerator). I believe even the YieldInstruction does this - although I may be incorrect. Where’s superpig when you need him?

A simple test would be to create a large number of GameObjects and attach a script that has Start as a Coroutine and then benchmark the FPS and see when the GC hits. Next, use the same number of GameObjects with an Update method.

I’ve sayd that if you make the coroutine wait MORE than one frame you execute fewer instructions.

WaitForSeconds(2) means that no code will be executed for two seconds.
I don’t know how unity does this internaly but it may be better than something like

Anyway, I’ve done no benchmark to compare both solutions. It’s just based on my understanding of how unity ( coroutines) work. But I’ll be interested in the result if someone take the time to do such a benchmark!

You do realize the irony in that statement right? :slight_smile:

That was sort of my point. This is something that would have to be tested extensively before you could say “this method is slower than that method” so, in general, I would hesitate to mention it off the cuff like that.

I don’t think this sort of answer has something to do on this sort of forum.
I’ve many things to do more interesting than starting a flame war.

Anyway, I’ve gived my personnal advice on this subject, so I’ll leave the OP do the pro and cons and do his own choice.
As I stated before, I don’t have any benchmark about this, but neither you do. This thread is going nowhere like that. So if it come a day you do it, just keep us updated.
I’d be pleased to be proved I’m wrong with real numbers (and why not a full project to reproduce?).

See ya!

Who said anything about a flame war? I was genuinely curious as to the result if you had done some tests yourself.

However - I’m not the one who brought it up in the first place so I don’t find it necessary to spend time proving or dis-proving what someone else said. I simply wanted to have a discussion - I guess you thought otherwise…

In theory,
Why would any coroutine be heavier on GC? Why would it not?

i think not, as a function called is a function called. it is what is inside that counts. No pun intended. In my mind a call to an empty function Update, may be slightly less heavy then one called via invoke because the invokeRepeating may require some rewiring (inside the engine, no matter how small) where update is very simply, fundamentally imbedded, already, in Unity. But overall, if any difference in efficiency exists, I would argue it is terribly small.

Any other theories?

The memory allocations related to using coroutines are incredibly minor and should not be the cause of any GC concerns. Just make sure to yield null instead of “0” to avoid boxing/unboxing when you just want to wait a single frame. Other than that, Coroutines are a great tool and shying away from using them would be a large mistake (adding complexity to the development of a project with virtually undetectable micro-optimization gains).

The O.P. is talking about a dozen or so objects running a coroutine. It would be crazy not to use them in my opinion. Shying away from an incredibly powerful tool (Enumerators) for the sake of GC performance is just hamstringing yourself because someone somewhere told you to avoid the dreaded GC at all costs (instead of at all reasonable costs).

For any remotely complicated class, chances are the spaghetti code you end up with in Update to avoid using Coroutines is going to have a larger performance impact than just using the coroutines would have (and dramatically increase the complexity of debugging in the long run).

No theory needed - a Coroutine creates an Enumerator whereas a method call with a void return type doesn’t create anything. However - as KyleStaves has pointed out, it’s negligible (so long as you yield null). My point about testing was to see how many Coroutines it took to trigger a garbage collection. My guess was that it would take a lot of them, if it ever triggered at all.

At any rate - the biggest gain you can get from Coroutines, in my opinion, is in use cases where you don’t HAVE to perform something every frame. This way, when there is nothing to do, the object truly does nothing (as opposed to calling Update and returning immediately).