Home > Enterprise >  Unity Crashes Because of For Statement
Unity Crashes Because of For Statement

Time:03-18

After I added this one for statement, Unity crashes, I've reopened and reran it several times, but it still crashes. Here is the for statement:

for (i = 0; i < 20; i  )
{
    player.transform.position  = Vector3.right * -1;
    i = 0;
}

I am new to Unity, so be as nice as possible because I kinda suck.

Thanks for you help

CodePudding user response:

Your loop is running infinitely. On each iteration you set your counter variable back to 0, hence it never stops and keeps decrementing your player position. Have you tried forcing the loop to quit at one point to see if your program still crashes?

CodePudding user response:

Your code results in an infinite loop. If you want to have a repeating function with a delay, you can use Coroutine. The YieldInstruction (yield return new WaitForSeconds(waitTime) in the unity document example) determine the amount of time you wish to wait. The sample code in the document prints infinitely with a 2 second delay; however, rewriting the condition of the while loop is one of the ways that helps you determine when a coroutine ends.

Another way to acheive it is using async/await. However, the instructions you can use for await are not as rich as yield instructions. Moreover, the last time I checked, a while true code with a print statment, keeps printing even when unity is not in play mode anymore.

CodePudding user response:

Well, of course you program crashes, you have an infinite loop due to always resetting

i = 0;

which basically makes it equivalent to

while(true)
{
    // move
}

since you never exit this loop you never allow Unity to move on in its execution -> The app and the entire Unity editor which runs in the same single Unity main thread completely freezes.


Since you say you want this to happen infinitely anyway, what you rather want is move this into Update which is called once every frame and then use Tim.deltaTime to convert your fixed value per frame into a value per second

// Speed in Units per second
// adjust this via the Inspector
[SerializeField] private float speed = 1;

private void Update()
{
    player.transform.position  = Vector3.left * speed * Time.deltaTime;
}
  • Related