Problem with "stun"-timer after player is being hit

In the 2,5D sidescroller I currently develop, I am trying to stun the player for a very brief moment of time once they get hit by an enemy (that also serves to play the “hit”-animation").

I started off by a simple collision script, reducing the players HP by 30 on each hit (player begins with currently 110). That worked just fine so far, each time the enemy touches the player, he loses 30 hp, but only once per touch.

Then I added an extra bit of code to my Update method in order to get the stun-timer in:

	if (IsHit)
			Hittimer = Time.time + Hitdown;	

			if (Hittimer >= Time.time)
				GetComponent<CharacterController>().enabled = false;
				Hitanim = true;

			if (Hittimer <= Time.time)
				IsHit = false;
				GetComponent<CharacterController>().enabled = true;
				Hitanim = false;

Hittimer isn’t initialized before that if-statement, Hitdown is set to 0.2f.
Hitanim is given to my Animation-script to handle the hit-animation.
IsHit is initialized with false. My enemy-script detects collision and sets IsHit to true once collision occures (simple OnTriggerEnter script).

My problem now is, I seem to have an error in the sub-IFs that I can’t find. The “stun” is permanent, as is the boolean for Hitanim. Though the boolean for IsHit instantly resets to false. The damage is done only once too, so I am quite sure that the issue is somewhere in those if-statements

I’d be glad for any help on it, or better methods to get my “stun” done, preferably in C#.

You could use a Coroutine. A Coroutine is a function that can extend it’s execution on a certain laps of time; in other word you can wait a certain amount of time before resuming it.

You can declare a Coroutine like this:

IEnumerator WaitForStunToEnd() {
    // Wait a frame
    yield return null;

    // Wait 0.2 seconds
    yield return new WaitForSeconds(0.2f);

To start a Coroutine use:


So In your case you just need set the damage taken, disable the character controller in your OnTriggerEnter AND start the coroutine.

In the coroutine, yield return new WaitForSeconds() for the time you need, then reenable the character controller.

Also if you don’t want your player to be hit while stun keep using your hit boolean and just set it to true in your OnTriggerEnter and set it back to false in your coroutine.