- Home /
For loop going based off of Time.deltatime?
how would i make my for loop go based of of seconds?
for example i did this but its not turning out right ( i am trying to transform a button to a certain point on the screen from a previous point)
var monsterOneRight : float = 100.0;
var monsterTwoRight : float = 150.0;
var moveRight_Speed : float = 2.0;
var actualRight : float;
var towerOneLeft : float = 100.0;
var towerTwoLeft : float = 150.0;
var moveLeft_Speed : float = -50.00;
var actualLeft : float;
var showMonsterButtons : boolean = false;
var showTowerButtons : boolean = false;
function Update () {
if (showMonsterButtons == true)
for(var i: float =0; i<=1000; i += (moveRight_Speed * Time.deltaTime))
Debug.Log(i);
if(i == monsterOneRight){
monsterOneRight = i;
}
You're going to have to be a lot more clear about what it is you're asking.
Answer by aldonaletto · Oct 22, 2011 at 10:40 PM
You're in the right path:
for (var i:float = 0; i <= rightTransform; i += Time.deltaTime*transformSpeed){
button1Right = i;
}
The variable i must be declared as float, and the parenthesis were mismatched (typo?). But the whole idea is right, you can use floats in for instructions as well. I suggest you to change the title to something like "How to use Time.deltaTime in a for loop?".
it lags my computer so much! is it unconventional to do something like this?
That's another problem: lengthy loops really slow Unity down. To avoid this problem, you should add a yield instruction inside the loop - it frees Unity until the next frame, when the system resume in the next instruction automatically. Unfortunatelly, yield instructions cannot be used inside Update. A possible solution is to place the lengthy loop with yield in a separated function - something like this:
function $$anonymous$$oveRight(){
for (var i:float = 0; i <= rightTransform; i += Time.deltaTime*transformSpeed){
button1Right = i;
yield; // free Unity until next frame
}
}
The yield instruction makes the whole function a coroutine. A coroutine starts when you call the function, and is suspended when the yield instruction is found; in the next update cycle, execution is resumed by the system right after yield, and goes ahead until another yield is found or the function ends.
Post the whole script in your question - or in a new one - so we can help you to adapt the code.
I didn't put all of it i put the parts that are needed for the for loop, because i dont want my script out there ha ha