Unity crashing when function runs

this function is being used to make sure an object waits for a certian number of seconds before it changes position, for some reason whenever this code is run unity crashes ? any ideas why ?

function wait(waittime : int){
	waittime = 0.000;
	var initialtime = Time.time;
	var finaltime = 0.000;
	var deltatime = waittime - 1.000;
		finaltime = Time.time;
		deltatime = finaltime - initialtime;

You’ve created an infinite loop.

Most game engines, including Unity, work something like this:

  1. Advance the game state by one frame
  2. Render game to screen
  3. Rinse and repeat 30-60 times per second

Your scripts are useful in step one. Unity hands you control of the main thread, which is very powerful but also a bit risky if you do something that causes a crash.

Usually, each script should perform some small, quick operations in Update. Anything that involves waiting is usually structured as a coroutine or timer check – after all, the game needs to keep running, even if your script is waiting!

For example, you could check: is this script suppose to start moving, yet? Okay, then we do nothing during this frame. That’s fine. You don’t have to make every script do something in every frame.

In your case, you’re looping based on Time.time, which is bad for two reasons:

  1. A wait on the main thread will hang your game until it’s finished, which is bad.
  2. Because Time.time updates only once per frame, your loop will actually never finish, which is why you’re getting a crash.