Smarter and Louder Missiles
Objective: allow missiles to target different enemies at once, and play sounds when fired.
Today we’ll refine the features of the missiles. One easy addition is adding sound when missiles are fired. We can just give the missile prefab an audio source that players an AudioClip on awake.
Improving the missile targeting is a little more difficult. Ever since missiles were introduced, they’ve had a tendency to both go after the same target. Notice how the both missiles momentarily aims towards the top enemy.
To fix this, we want to disallow missiles from targeting the same enemy, if possible. We’ll need missiles to be able to communicate with each other, which we can do by adding a static variable to the Missile class. Static variables are shared between all members of the class, so any Missile can access this same HashSet that keeps tracking of what enemies are being targeted.
When missiles choose a target, they will add it to the set.
Now whenever a missile gets the list of enemies, it will also turn that list into a HashSet and then use the method ExceptWith to subtract the enemies that are already targeted by other missiles. If there’s some enemies remaining afterwards, then this missile will only go after those “not targeted” enemies.
Finally, we need to make sure the static hash set is cleaned up correctly. We don’t want it to get filled with potentially null gameobjects of enemies that have been targeted before.
We’ll create a helper method that better controls what happens when a missile is destroyed. DestroySelf will include a line to remove that missile’s current target, and is called when the missile collides with a target. This way, missiles that damage but do not destroy an enemy will remove their target from the hash set so other missiles can target it again.
Also, if a missile is targeting an enemy that somehow dies by other means, then we also want to remove that enemy from the hash set.
Here’s the new behavior of missiles. Now they will always try to pick different targets, which is much more satisfying to watch!