We are now at a point where we want to add some variety to our Enemy so that we don’t bore the player a ‘rain’ of targets.
A simple way to do this is to add some extra move options to our Basic Enemy. In this example, we have some of the enemies target the Player’s position when they recycle. With a few lines of code, we with give the impression that the Player is being recognized by the enemy and not just there.
First, we are going to need a couple new Variables. There is _trackerChance so the Designer can adjust and tweak how often a newly spawned Enemy becomes the Tracker Variant. We include a Tooltip with it so the Designer will know how the INT will work with the code. And we have a handle for the _target or Player. I didn’t call it _player because we may decide that we want it to Target other objects later.
Next, We have a new Awake method. Awake is the first method of any MonoBehavior to run and is run only once for the object it attached to. By placing this code in Awake, It will happen once and before any other part of the class.
Here we are getting a random number between 0–99 and checking it against the _trackerChance. If it is above that chance, this Enemy becomes a Tracker variant until it’s object is Destroyed or the Game is restarted. If it is a Tracker, we find the Player by the “Player” tag and assign it to _target. We don’t have to explicitly define it as NULL if it is not a Tracker, but I felt it best to make sure the handle variable was clean.
Finally, In the Respawn method (which recycles Enemies to the top if they are shot down), We add a simple NULL check to see if we have to adjust our aim for the Enemy. This will cause the Enemy to face the Player the moment they recycle and from there on move Forward on that line. The player can move of course, but the Enemy will stay on that path until they are recycled or shot.
This barely counts as “AI” in the game world, but this is just a start.