In this article, we would make all enemies will attack Player when Player is in range. Before this function, the enemies are passive on attacking besides they were attacked.
It would need 2 parts to finish this function:
- A new attacking animation that would be triggered by any state.
- The timing of calling the attacking trigger.
Attack animation state
First we need a new animation state to all enemies.
We can simply create one by coping the Attack state animation and paste it back to Animator. Then rename it as “DetectAttack” and set the transition from Any State to it.
Next, create a trigger called "DetectPlayer” and assign it to the transition from Any State to DetectAttack.
Set the transition from Any State to DetectAttack with no Exit Time and set the transition duration to 0.
Then from DetectAttack to Idle, keep Exit Time and also set the transition duration to 0.
Once done, we can adjust the code to make this works.
Attack when detected
Open Enemy script, and first we need a bool to start the animation only 1 time per detection.
Then create a new method to trigger enemies start attacking.
The next is to call this method when Player is in detecting range, and using the bool to make it only be called once.
And make enemies disable attacking mode when Player is out of the range, then set the bool of detection back to false.
All set! Our enemies would be aggressive and harder to defeat.