How to set up enemies that can shoot projectiles triggered by animation event in Unity.

Let’s go over how to set up an enemy that can fire projectiles based on an event triggered by the animation.

This article continues to build on the enemy behaviour from this article.

First, create the projectile by dragging in the first frame of the projectile animation. Set the order layer to ensure it is visible and add a box collider:

Adjust the collider:

Create a script called Projectile and attach to the game object:

Open up the Projectile script and add:
-float for the movement speed
-int for the amount of damage the projectile will do
-Vector3 for the direction of the projectile

In the Start function set the projectile to destroy itself after 5 seconds and in the Update function set the projectile to move in the set direction:

Add an OnTriggerEnter function which will check for IDamageable and if not null, call the damage function. Also create a function to set the direction of the projectile:

Create two new layers: Enemy and EnemyAttack. Set the layers to ignore each other:

Set the layer on the projectile to EnemyAttack:

Create a script with a suitable name for the enemy type and attach to the enemy:

Open up the script and set it to inherit the Enemy base class and add:
-Gameobject for the projectile
-Transform for the position where the projectile will instantiate

Inside the Update function check if the player is within combat distance. If so, enable combat mode. Add a public function for firing the projectile:

Add the projectile object and fire point transform to the script on the inspector:

Add the EventReceiver script to the graphics object on the inspector:

Open up the EventReceiver script and add a function firing the projectile:

Add IDamageable to the player script:

Lastly, add the event to the attack animation of the enemy:

Good luck!

Unity / C# Game developer