While loop crashing unity even with a end specified in code.

Hi, i am trying my hand at while loops as i dont usually use them when coding in unity. However i get the same problem being that it always crashes.

public bool hit;

// Start is called before the first frame update
void Start()
{
whiletest();
}

// Update is called once per frame
void Update()
{

}
private void OnTriggerEnter2D(Collider2D collision)
{
hit = true;
}
public void whiletest()
{
while (hit==false)
{
Debug.Log(“not hit”);
}
Debug.Log(“hit”);
}

This is my code, i am trying to set the hit bool to false once it collides with a object, i have confirmed that the boolean will be set to true once it collides and i have used coroutines to see that it only crashes once the whiletest method is called. Any advice is appreciated

THis will not work at all. Once your while loop starts, nothing happens until the while loop ends. No collisions will happen until after the while loop ends. No boolean will be set until after the while loop ends. You need to either add code inside the while loop to set “hit” to true, or else you need a return/yeild statement inside the loop.

1 Like