Doing stuff once in Update()?

I have some objects lerping between different sets of points.

Every time the object reaches a new point I want the object to rotate ONE time. However, this can’t be done in Update(), since the object would then just be turning like mad because it rotates every single frame.

I can’t think of any solution to this :?

Don’t use Update, use coroutines. (To those keeping score: yes, I’ve said this about 100 times now. :wink: I almost think UT should just disable Update, it gets abused so much…)

–Eric

IMO the coroutine stuff isn’t very well described in the scripting reference… :?

Alright, I am trying to do the following:

function Update() {
	
tid += tid2;

if (i+1 < splinearr.length) {
	for (var j : int = 0; j < childarr.length; j++) {
		if (tid * smooth <= 1.0) {			
			yield RotateLetters();


 			childarr[j].transform.position = Vector3.Lerp(splinearr[i].transform.position, splinearr[i+1].transform.position, 				tid*smooth);
		} 
		else {
		i++;
		tid = 0;
		}

		
	}
} 
}

function RotateLetters() {
	
	for (var i : int = 0; i < childarr.length; i++) {
		childarr[i].transform.Rotate(Vector3.forward*90);
	}
	//yield; 	
}

I’m thrashing through this myself, this is the most helpful page I’ve found so far:

http://blog.equals-equals.com/?p=8

I am reading that as well :slight_smile:

I have done some experimenting with coroutines and I can see several places where my code will benefit, but I’m having trouble wrapping my head around how it can be used as an alternative to Update().

Hi Eric,

I’m going to ask something here that I know will get you sighing slow and long and I can almost see your shoulders drooping despondently as I type this, but here goes…

For those of use coming here with an ActionScript background, can you describe how a coroutine would achieve the following better, I feel I’m on the verge of understanding something big - but I’m just not there yet. (The links above only really refer to a wait for key example).

Are you saying this:

function Start () {

   // Put a Ball on the left-side of the screen here.

}

function Update () {

   if(Ball <= rightSideOfScreen){
      moveTheBallToTheRight();
   }

}

function moveTheBallToTheRight() {

   // move the ball to the right here.

}

Is better done like this:

function Start () {

   // Put a ball on the left-side of the screen here.

   moveTheBallToTheRight();

}


function moveTheBallToTheRight() {

   while(Ball <= rightSideOfScreen){
      // move the ball to the right here.
   }
   yield;
   
   moveTheBallToTheRight();

}

?

If so, why?

  • I’m not even sure if the above example would work because we are calling a function from within the function - but my point, I guess, is how does a coroutine needed to be executed every frame (or physics-step) get called if not from Update or FixedUpdate? (let’s say that Unity did disable Update).

Also, the above example decentralises the conditions, making the process more difficult to keep track of (more fragmented) right?

Ok - now breath in…

I also have trouble getting my head around using coroutines. I am under the impression that I can do everything in the update instead of using coroutines if I want to. I also don’t think it would be less efficient in the update either. (I have only used coroutines to use the WaitForSeconds method). I do agree that coroutines may result in more readable code, but other than that, I fail to see why the most experienced and knowledgeable members of the forum (Eric, Dreamora, Andeee and company) keep on telling us to use coroutines.

@Eric, you would be doing the community another great favor if you write a short description for the wiki on couroutines: advantages and when to use them (preferrably in bullet points :))

ya- like ivkoni said above.

My current approach is to use Update to list all the things I want to do each step as a series of function calls, and use the functions to do all the dirty work:

function Update(){

movePlayer();

moveBaddy();

if(Baddy hits player){

killPlayer();

}

}

Someone has already written a bit on the wiki about when to use coroutines: http://www.unifycommunity.com/wiki/index.php?title=General_Performance_Tips#Scripting.
In short, doing stuff in Update() (particularly if you’re doing a check to see if your bad guy killed your mans, as in RobbieDingo’s example) has to be checked and run every frame. If you stuff that code inside a coroutine that gets called when the baddie collides with your player, you aren’t constantly asking Unity to check for you. As an analogy, say you’re going to a movie with your friend, but he’s not ready. You can stand outside his door and constantly ask, “Are you ready yet? How about now? Now?” or you can run down to the convenience store to buy snacks to sneak in and have him text you when he’s ready. The latter scenario is obviously preferable to the first. You’re not wasting his time by constantly bugging him, and you can get things done while he’s getting ready. That’s when and why you’d want to use coroutines.

Thanks,

I’ll go check that wiki link now.

Maybe it’ll help me to understand this, particularly why your analogy has saved anything, I mean surely this just shifts the check that Unity has to perform elsewhere?

ie. your friend now has to check if he is ready - “Am I ready yet? How about now? Now?”, then tell you when he is… like I said above:-

it “decentralises the condition-checking, making the process more difficult to keep track of (more fragmented) right?”.

(PS. I get it for situations where Unity can fire a function at the moment a particular situation occurs, like onCollision, but not for a situation where you need to manually check each step).

EDIT: I guess this helps (from the link):

“Coroutines are your friends. Coroutines have only a tiny overhead and can be preferrable to an Update method that is called all the time needlessly. For example, if you had a script to fade in and out a light on command, you could do the fading in a coroutine instead of in Update. That way, most of the time when the light is not fading, the script takes a minimum amount of performance. If the fading was done in the Update function, you would be inefficiently polling to see if there is fading to be done.”

I think they make sense for some things, but I don’t see the point of replacing ALL of your update calls with coroutines.

My first game had over 20 update calls, and they didn’t seem to affect performance.

Your friend doesn’t have to check if he’s ready. He’s got a series of steps to perform (put on underthings, put on shirt, put on pants, put on shoes, grab wallet, phone and keys) and then he’s done, just like your coroutine (move x units to the right, move y units up).

So the advantage comes if you pretend that you’re the Unity engine. Instead of presiding over your friend’s ready-making, you can skip over his business and presume he’ll put his pants on correctly and go about your business. The flashing light example is a great one because it’s something that, to do in Update, requires you to keep track of a bunch of state variables. It’s almost like the difference between turning on a strobe light once and flipping the light switch on a standard lamp manually as quickly as possible. Which would you prefer?

Obviously, it’s not necessary or perfect for every situation (nothing is), but when you have a large number of objects going around and particularly if you’re messing about with textures or doing pathfinding or any kind of computationally heavy activity, it’s nice to give Unity a break sometimes.

Perhaps if the friend in the analogy were a she rather than a he (preferrably a hot blonde blue-eyed, fit, young girlfriend) it would be much easier for us to understand.

I would like to see actual performance measures though to be convinced that coroutines are faster. If statements on a state variable will have absolutely minimal impact. I would also imagine that coroutines introduce some slight overhead as well?Also as far as execution in parallel with a coroutine goes, how reliable is that?

I still don’t really understand this.

I need to move some objects (doing multiple lerps after each other), but every time the object reaches an end I want the objects to rotate, but only once.

I can’t get it to work :frowning:

Sorry the_marsbar,

We started to hijack this thread for other conversations.

When you say “every time the object reaches an end I want the objects to rotate, but only once”, do you mean rotate all the way around (360 degrees) or do you mean you want it to rotate just a bit - then move to the next waypoint?

This is probably a great example of how NOT to do it, but it’ll work…

Attach this script to the object you want to move, and define target as being another object (think of target as being an invisible magnet) - once you see how this works, you could make the target just be a Vector3 - it does not actually have to be a gameobject, but it helps to see how this is working maybe?

var target : Transform; // link this to a game-object in your scene

private var now : float;
private var currentWaypoint : int;

private var waypointArray = new Array(Vector3(0,0,0), Vector3(10,0,0), Vector3(0,10,0), Vector3(0,0,10));

function Start () {
	
	now = Time.time;
	currentWaypoint = 0;
	
}


function Update () {
	
	if(currentWaypoint != waypointArray.length-1){
		// if we have not reached the end of our waypoint list
	
		if(transform.position != target.position){
			// if we have not reached our invizible target
		
			lerpMeToTarget(transform, target);
	
		}else{
			// if we have reached our target
			
			// flip around 90 degrees (just once)
			transform.Rotate(Vector3.forward*90); 
			
			// remember time, right now
			now = Time.time;
			
			// increment pointer to next waypoint
			currentWaypoint += 1;
			
			// move our invizible target to next waypoint, this is why it will rotate just once, because on the next update, we will not be at the target's position anymore...

			target.position = waypointArray[currentWaypoint];

		}
	}
}


function lerpMeToTarget (me : Transform, targ : Transform){
	
	transform.position = Vector3.Lerp(me.position, targ.position, (Time.time - now) /10);
	
}

OK - there you go - now if anyone wants to show ME how to do this using coroutine, I’d probably learn a lot…

Hope this helps Mars.

No problem, your posts were useful for me too :slight_smile:

This is the code without any rotation:

function Update() {
	
time += Time.deltaTime;
	if (tid * smooth < 1.0) {
		childarr[j].transform.position = Vector3.Lerp(splinearr[rotationpoint].transform.position, splinearr[rotationpoint+1].transform.position,	tid*smooth);
	} 
		
	if (tid * smooth >= 1.0) {
		if (rotationpoint+2 < splinearr.length) {
			rotationpoint++;
		} else {
			i = 0;
			}
			tid = 0;
		}
	}
}

When the objects reach the end of each lerp I want them to rotate (say, .transform.Rotate(Vector3.right90) for instance).

However, if I do the following, the objects just keep turning, and not only doing the rotation one time which is what I want. I tried using a bool to check to see if the objects had been rotated - didn’t work either:

function Update() {
	
time += Time.deltaTime;

	for (var j : int = 0; j < childarr.length; j++) {
		if (rotationpoint == 0) {
			childarr[j].transform.Rotate(Vector3.forward*90);
			
		if (rotationpoint == 1) {
			childarr[j].transform.Rotate(Vector3.left*90);
		} 
	}
		//... and so on. Will be replaced by a switch-case. Just wanted to see if it worked (and it didn't).
	
	if (tid * smooth < 1.0) {
		childarr[j].transform.position = Vector3.Lerp(splinearr[rotationpoint].transform.position, splinearr[rotationpoint+1].transform.position,	tid*smooth);
	} 
		
	if (tid * smooth >= 1.0) {
		if (rotationpoint+2 < splinearr.length) {
			rotationpoint++;
		} else {
			i = 0;
			}
			tid = 0;
		}
	}
}

I really need some help here. I can’t really see how I can get rid of the Update() function, because I want the LERP to happen every frame… And coroutines can’t be called within Update()…

Here is my take on this
To understand Co-routine you must research

one advantage is you can set the “update frequency”

so unity is not checking as quickly as within the Update() routine

public Wallet wallet;

void OnGetWallet(){
	Debug.Log("yippy i got my wallet");
}

IEnumerator WaitForMyWallet(float htz){
	yeild 0;
	while(wallet==null) {
		yield return new WaitForSeconds(htz);
	}
       OnGetWallet()
	
}

void Start(){
	StartCoroutine( WaitForMyWallet(5f) );
}

another way to deal with this is dig deeper into C# events