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

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.

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().