How do I make it so that it wont edit a variable again for a certain ammount of time? C#

here is part of my script…it works…except by the time it kicks in it has already collided twice so instead of subtracting 10 hp it subtracts 20…this wouldn’t be a big deal except I plan to switch to a hearts system later with much lower numbers

if you want to use this code you will need the following
-hp variable
-knockback variable
-isstunned variable (movement controls must be in an"if(isstuned >= 0)" statment and variable must be set to 1)

Blockquote

//On Collision
IEnumerator OnCollisionEnter(Collision  collision)
{
	//with bandit
	if (collision.gameObject.tag == "Bandit")
	{
		//if bandit is to the right
		if (Physics.Raycast(transform.position,Vector3.right,10))
		{
			//take controls away from the player
			isstuned -= 1;
			//knock player to the left
			rigidbody.velocity = -transform.right * knockback;
			//wait 1 second, minus 10 hp, and then print to console for debugging
			yield return new WaitForSeconds(1);
			hp -= 10;
			print("-10 hp struck by bandit from the right"); //debug
			//give controls back to the player
			isstuned += 1;
		}
		//if bandit is to the left
		if (Physics.Raycast(transform.position,Vector3.left,10))
		{
			//take controls away from the player
			isstuned -= 1;
			//knock player to the right
			rigidbody.velocity = transform.right * knockback;
			//wait 1 second, minus 10 hp, and then print to console for debugging
			yield return new WaitForSeconds(1);
			hp -= 10;
			print ("-10 hp struck by bandit from the left"); //debug
			//give controls back to the player
			isstuned += 1;
		}
			
	}

}

Blockquote

I hope my notes are informative to those wanting to use this ^_^…(does need a minor fix though so you might want to either wait on a fix or attempt it yourself lol)

Have a bool isDealingDamage = false.
Change your if to: if(collision.gameObject.tag == “Bandit” && !isDealingDamage)
On the first line of the if(){}block set isDealingDamage = true;
On the last line of the if(){}block set isDealingDamage = false;

Since both if blocks inside your if block have a WaitForSeconds(1) in them, there will be a ‘buffer’ of one second before damage can be dealt again.

You can create a dead time during which further collisions are ignored:

public float deadTime = 0.2f;
float nextTime = 0f;

//On Collision
IEnumerator OnCollisionEnter(Collision  collision)
{
    //with bandit
    if (Time.time>nextTime && collision.gameObject.tag == "Bandit")
    {
        nextTime = Time.time + deadTime; 
        //if bandit is to the right
        ...

Adjust the deadTime variable to avoid multiple damage for the same hit.

I really like both of your guys solutions…I ended up going with joshua’s solution so I checked is as “right answer”