Setting up our EnemyAI: State Machine and Attack Behaviour!

Marcus Ansley
2 min readAug 20, 2021
Does need some audio-visual feedback (and could probably be sped up a bit)

I recently made a couple of additions to the EnemyAI script we worked on previously. Namely, I’ve incorporated a ‘state machine’ using an enum to store the enemy’s current state (EnemyState) and a switch statement within the FixedUpdate method to determine each enemy’s behaviour. They’ll start off in ‘Chase’ mode (which allows them to move towards the Player) before entering ‘Attack’ mode if the Player gets within the radius of a SphereColldier.

For this attack functionality, I’m using OnTriggerEnter and OnTriggerExit to change the _currentState variable’s value appropriately. If we’re in Attack mode, the Enemy will attempt to deal damage to the player via a reference to the player’s Health script (which we’re attempting initialise in the Start method). There’s also a quick and easy cooldown mechanism on this attack method which I’ll run through:

What’s stopping this Health.Damage() method from getting constantly called within the FixedUpdate method is this ‘if (Time.time > _nextAttack)’ check, which is checking to see whether the current time since the game started (Time.time) is greater than the timestamp we’ve set in _nextAttack. So to begin with, Time.time is going to be bigger than the initial value of _nextAttack (-1) and so the code will get called. Then, beneath our call of the damage method, we reassign the value of _nextAttack to equal the current time that’s passed plus whatever our _attackDelay is (in this case, 3 seconds/3f). So for instance, if 45 seconds had passed _nextAttack would now have 48 assigned to it, meaning the code would have to wait at least 3 seconds before damage can be dealt again.

Once we have our code set up, all we then need to do is hop over into Unity and assign any of those serialised private variables, such as the _attackDelay and _damageAmount, to tweak the enemy’s attack behaviour until we’re happy with it. Since these aren’t hard-coded values, we could easily add some variation between different enemy types if we wanted 😉

I’ll include the full code below:

--

--

Marcus Ansley

Game Developer | Game Design and Literature Graduate