While loop causing Unity to hang up?

void OnCollisionEnter(Collision colInfo)
{
if (colInfo.collider.tag == “Infection”)
{
Debug.Log(“IF STATEMENT”);
health = health - 1;
Die();
}
}

    void OnCollisionStay(Collision stayInfo)
    {
        while (stayInfo.collider.tag == "Infection")
        {
            timer = 0;
            timer += Time.deltaTime;
            if(timer == 1)
            {
                health -= 1;
                timer = 0;
            }
            Die();
            Debug.Log("WHILE STATEMENT");
        }        
    }

    void Die()
    {
        if (health <= 0)
            {
                Destroy(gameObject);
                Instantiate(infection, transform.position, transform.rotation);
            }
    }

Not exactly sure why it’s having issues… I read to be careful with while statements and this really doesn’t seem like it’s running infinitely. It runs fine with the if statement in OnCollisionEnter but doesn’t work with the while statement in OnCollisionStay.

hi @coltonatlas

If you check the manual for OnCollisionStay:

There it says:

“OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.”

So every frame your collision happens, your while loop gets called. Not exactly what you want most likely.

Here is a modified example, that causes typical contact damage.

Each frame player has contact to some specific collider, counter value goes up. After a while timer gets full, and hitpoint is reduced. Timer is zeroed, and starts again.

If player stays in contact long enough, he runs out of energy and dies.

public float health = 10f;
public float timer = 0f;

void OnTriggerEnter(Collider other)
{
	if (other.gameObject.tag == "Infection")
	{
		timer = 0f;
	}
}


void OnTriggerStay(Collider other)
{
	// Every frame overlapping infected
	SufferInfection();
}


void SufferInfection()
{
	timer += Time.deltaTime;

	// On timer full, cause damage
	if (timer >= 1f)
	{
		health -= 1f;
		timer = 0;
	}
	
	// When
	if (health <= 0) Die();
}


void Die()
{
	Debug.Log("You died!");
}