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.
Order of Events for the Script Lifecycle in Unity 2021
Per Unity: https://docs.unity3d.com/Manual/ExecutionOrder.html
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.