Script causing Unity to freeze?

Hello,

I have been attempting to figure out ways to make a character stop moving upon death, so that is what I am trying to do in the while loop of the Update method in the screenshot I attached below. The reason I just do not straight out destroy the game object immediately is there is a death animation that I first want to play before the object disappears, but obviously, I do not want the object to continue translating forward as the death animation is playing.

For some reason, when I modify the Update method to include this while loop, Unity freezes completely when I press the run button, and the run button never even turns blue. I have to restart my computer each time this happens since Unity is just frozen! If I change the code to not have the while loop, Unity runs just fine. I am using 2019.4.1f1 if that is of any use to you.

Thanks for reading, and I would definitely appreciate any help to solve this!

You didn’t attach the screenshot, but also, use code tags and not screenshots to post code.

Oops sorry, here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Attacker : MonoBehaviour
{

    [Range(0, 1)] [SerializeField] float walkSpeed = 1f;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        bool isDead = gameObject.GetComponent<RobotHealth>().GetHealth() == 0;
        while (!isDead)
        {
            transform.Translate(Vector2.left * walkSpeed * Time.deltaTime);
        }

        transform.Translate(0, 0, 0);
    }
}

Yeah, that’s what I figured. Your while loop is going to just run continuously… and never return to the main game loop. It’s just stuck, constantly checking to see if isDead is false, but never actually recalculating isDead’s value or even running any other code in the game.

Make it an if statement, and not a while loop. Update() gets called every frame, so you only need to check that condition once every frame.

(You might also have trouble with your == statement above that if your health is stored as a float and/or if it isn’t clamped at 0. Using == to compare floats is generally unreliable due to floating point imprecision.)

1 Like

Oh ok, that makes a lot more sense. I switched to an if else statement so now my game is able to run again. Also, thanks for the pointer on the health, my health component is stored as a float so I used Mathf to round it to an int. Thanks for your help!