transform.translate not working in for loop

hi every one
i’m a beginner and it’s my first game .
when player collides with gameobject that you see in the picture the elevator that is a plane object moves up but not much for example 2 units (i want y axis of them to be 2).
the problem is that ,the transform.position and transform.translate works out side the for loop but not inside it .

these are my objects

and the code

void OnCollisionStay(Collision collision){
        float i;
        if (collision.gameObject.CompareTag ("player")) {
            //elevt.transform.position=new Vector3(0,2 ,0);
            //pLAY.transform.position=new Vector3(0,2,0);
            //transform.Translate(0, Time.deltaTime  ,0);
            for(i=1;i==4;i++){
                i=Time.deltaTime;
                transform.Translate(0, Time.deltaTime  ,0);

            }
        }
    }

i hope i could explain it properly with my bad English

for(i=1;i<4;i++){
its “from i equals 1, while i is less than 4”
not “from i equals 1, while i equals 4” (because it doesn’t equal 4)

1 Like

thanks dude ,I remember I did the same mistake in the past and some one explained me why it can’t equal 4 , but I can’t remember why !
can you explain it for me ,please

for loops are a shorthand. When you write a for loop that looks like:

for (A;B;C) {
body
}

What the compiler actually sees is more like:

A is executed before anything else
loop:
if B is true, then the body is executed; if it’s not, break out of the loop
execute C
go back to loop

If you step through your code loop by loop, you can see that i is set to 1, and then it compares (i == 4) which comes out to false, so it immediately breaks out of the loop.

1 Like

I’m sure you can be a great teacher :wink: :slight_smile:

I tried the correct form of the code ,now when I want to test it in the game unity stops responding
:frowning: :cry:

When Unity freezes like that, that almost always means you’ve created an infinite loop. In my example above, that means that B is always coming up as true. If you step through it loop by loop, you should be able to see that i is being re-set every time the loop runs to Time.deltaTime, so it never reaches 4. So, it loops forever. To fix that issue, you’ll want to remove i=Time.deltaTime

But, looking at the function, I think you probably don’t want that loop there at all. I’m trying to guess what your function is supposed to do - is it supposed to move the thing forward as long as it overlaps the player?

1 Like

yes almost ,I want it to work as an elevator
when player collides ,or overlaps with the empty game object the elevator object goes up.