To check which Animator state is currently active, follow these steps:
- Import the character to Unity.
- Create an Animator Controller for it or use an existing one.
- If you want your character to react to hits, follow the Using transitions from Any State to play hit reactions recipe.
- In this recipe, we are going to use the healing action as an example. Create a new script and call it Healing.cs. In this script's Update() function, first we check if player pressed the H key. Then we check if our character is playing in the proper Animator state and saved in the public stringhealingAllowedState variable. We also check if a healing action is not active because we don't want to stack healing actions. If all these conditions are met, we start a healing coroutine:
if (Input.GetKeyDown(KeyCode.H)) { if (anim.GetCurrentAnimatorStateInfo(0).IsName( healingAllowedState)) { if (!isHealing) { StartCoroutine("Heal"); } } }
- The IEnumarator Heal() coroutine is responsible for increasing our Spider's hitPoints in time:
isHealing = true; Enemy enemyScript = GetComponent<Enemy>(); while (enemyScript.hitPoints < (float)enemyScript.initialHitPoints) { enemyScript.hitPoints += healingSpeed * Time.deltaTime; yield return null; } enemyScript.hitPoints = enemyScript.initialHitPoints; isHealing = false;
- Assign the script to the Spider character.
- Play the game and press the H key to start the healing action. Our character needs to be in the SpiderIdle state (the public string healinAllowedState is set to Base Layer.SpiderIdle in the Inspector).