Updating AI Script for Object Pooling in Unity 2021

In previous articles, we’ve fleshed out the animation, navigation, and take cover features of our RobotAI script.

In this article, we’ll update it to be compatible with object pooling system in the SpawnManager script that I’ll cover in my next article.

I need a public method that my SpawnManager script can access to trigger the RobotAI script to reset its values and disable the game object.

The ResetValues() method does most of the work here.

The reason this exists instead of just being in the ReachedEnd() method is that conceivably there may be other reasons in the future we may want to reset the values without reaching the end point being true.

As discussed in my previous article, the OnEnable() method will execute before the Start() method.

I’ve used my Start() method mostly for when the game object & script are first created to initialize values and do null checks.

The OnEnable() method will come into play for object pooling, which will disable the gameobject once it reaches the end of the scene.

From there, when the game object needs to be reused, it will be re-enabled, thus OnEnable() makes perfect sense to target the behavior at that time.

Due to _navMeshAgent being initialized in the Start() method though, thus being null in OnEnable(), we need to do a null check and avoid triggering this code that only matters long after Start() has run and the game object has been disabled in preparation for reuse.

And that’s it, see you in the next article!

ADDENDA: I also added the Rigidbody and Capsule Collider components to my Robot prefab!

Otherwise, the collider on the Spawn_Manager game object will not trigger.

For isTrigger to work on a collider, either the game object it is attached to or the game object that has collided with it must have a rigid body.

If one or both do, the functionality works.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store