- Home /
How to delay a line of code.
Hi I need to know how to delay a line of code and heres the code im using its in java. So heres what I need, I need to delay the transform.Translate for about five seconds, so if you can do this for me it would be so much help. Thanks
var speed : float = 0;
function Update () {
transform.Translate(Vector3(0,0,speed) * Time.deltaTime);
}
Well, it would depend on how you are triggering it. You could set the translate into a boolean, so when you collide or do something else, you could call that boolean to be false which will cut off the translate. And within the function that called the boolean to be false, you could put a 5 second timer on that with deltaTime or WaitForSeconds() to reset the boolean back to true.
Answer by whydoidoit · May 31, 2012 at 07:50 PM
EDIT Per Wolfram's point - my first answer was not a good plan :)
However, it strikes me that perhaps you want the speed increase to be delayed by 5 seconds - and then ramp up as it ramped over that period. In which case you need a rollling buffer of the speed value:
var speeds = new List.<float>();
function Update() {
speeds.Add(speed);
if(Time.time >= 5) {
transform.Translate(Vector3(0,0,speeds[0]) * Time.deltaTime);
speeds.RemoveAt(0);
}
}
I wondering what effect you are try to achieve though - feels to me that there might be a better way...
Putting Invoke() into Update() is a resource hog, spawning a delayed call to $$anonymous$$ove() each frame. So for the 5 seconds delay and a framerate of 60fps, 300 coroutines are spawned, before even the first one is actually executed. Invoke() is better suited for delayed events that are triggered only once.
Oh I agree - and hence my comment - I was presu$$anonymous$$g some kind of snake follow animation - but on looking at the code again, it probably isn't right.
Now that's what I was trying to do with my first answer - but totally missed it ;(
Answer by Wolfram · May 31, 2012 at 09:33 PM
Assuming by "delay" you merely mean "I don't want it to be executed during the first 5 seconds", you can do something like this:
function Update () {
if(Time.time>=5)
transform.Translate(Vector3(0,0,speed) * Time.deltaTime);
}
Time.time contains the total time since your game started. If you want to measure the time from a different point (for example, if your Update() is part of an object that is being instantiated), you can store the value in Start() with startTime=Time.time, and then use the difference (Time.time-startTime) in Update.