this script make unity crash

hi guys, I'm still a novice, I know that somehow I've made a mistake, I need some help: I want a platform to move when I call this function, however 1/2 of the time unity crashes. How can I make the platform move to a direction to another if OnTrigger is called by an OnTriggerEnter? I should use a while, but how? Edit: FIXED BY USING YIELD - however now the game seems to freeze every 4 seconds for 0.5 seconds, what's the problem?

var muovi : boolean = true;
function OnTrigger() {
    //muovi = true;
    if(ontrigger && muovi){
        //Debug.Log("urtato");
        while(muovi){
            transform.position = Vector3.Lerp(transform.position, arrivo, Time.deltaTime * velocita);
            yield; // l'oldissimo wait(1)
            if(Vector3.Distance(transform.position, arrivo)<= 1){
                muovi = false;
            }
        }
        while(!muovi){
            transform.position = Vector3.Lerp(transform.position, partenza, Time.deltaTime * velocita);
            yield; // l'oldissimo wait(1)
            if(Vector3.Distance(transform.position, partenza)<= 1){
                muovi = false;
            }
        }

    }
}

OK, that's very strange, I don't have this problem if i comment (with /* and */) this code, everything works fine. WHY!? it's really strange

2 Answers

2

You wrote an infinite loop. Putting a yield statement in the while loop will allow time to pass, so that the loop should work. By the way, you don't need a separate OnTrigger function, you can just put that in OnTriggerEnter, which can be a coroutine.

yeah In fact I've fixed this way :D however something strange happens sometime, seems that the yield freezes the game every 4 seconds for 0.5 seconds, I don't know how to solve this problem, I'll update the code

–

I don't see anything offhand that would cause that; certainly yield doesn't do that.

–

You don't want a loop. The engine is already looping for you. Put

transform.position = Vector3.MoveTowards(transform.position, arrivo, Time.deltaTime * velocita * 0.001);
if(Vector3.Distance(transform.position, arrivo)<= 1){
      muovi = false;
}

in Update().

There's nothing wrong with a loop, and using Update is not what Volt3 wants, since Update runs every frame, and the function is written so that the loop only runs when OnTriggerEnter occurs.

–