Web Class: How to Pool Objects in Unity

Web Class: How to Pool Objects in Unity

Transcript Part 1

Even though we worried about making the bullets not last forever, so they’re not going to use very important space in memory, there is something else we have to worry about. Every time we add a bullet to this game, every time we do this instantiation process, it takes some time for Unity to get that element, to put it inside the game, and make it work, okay.

So actually creating and deleting elements, they are expensive operations. So you have to avoid that as much as possible. And at that moment, you might ask yourself, okay I’m a bit confused now, the bullet is something that has to be instantiated, but I have to avoid instantiating things. And it sounds funny if you say it, but what you have to worry about is pooling objects. And that pooling of objects is as follows.

You are going to have a little manager, something that is going to hold a certain object, a bullet, for example, then it’s going to preload a certain amount of objects. So maybe you want to preload 20 bullets, for example. And you’re going to make these objects inactive. They’re going to be kind of dormant. They’re going to be unavailable for use. Basically they are sleeping, and they are hidden in the game. And every time you want to spawn a bullet, instead of instantiating, you’re going to get a bullet from the pool of objects, because we already have one available. So that bullet is going to be activated, and you can do whatever you want with it. So, it might seem a bit confusing, a bit complex for you to understand that, maybe if that’s your first game, or one of your first courses you’re taking on game development, but this is one of the most important subjects in game development, which is object pooling. It’s going to save you lots of processing power. And memory as well, okay.

So, we want to make a pooling manager. So I’m going to come here in the Hierarchy. We need to right click, and need to choose create empty object. We’re going to take this game object from, outside the game controller, it’s going to be right here, and I’m going to rename that, let’s see, PoolingManager, or ObjectPoolingManager, or ObjectPooler, whatever name you think is going to work well. I’m going to call it ObjectPoolingManager, okay. We hit enter, it’s in the position 0,0,0. It’s not going to make any difference later, but still, let’s leave it like this. And now we need to make a script for it. So I’m going to the scripts folder, I’m going to right click, select create, C# Script, and then ObjectPoolingManager and then hit enter. And before we move forward, we’re going to make a folder. We’re going to organize these scripts. So I’m going to right click, select create, folder. I’m going to name this as game. And I’m going to select both the bullet and the player and drop it here. And I’m going to make another folder, and I’m going to name that Utils. Okay, I’m going to put the ObjectPoolingManager inside there. I worry a lot about folders because it’s important to keep things organized. And now that we did this, we’re going to put a reference to that ObjectPoolingManager. We need to drag and drop the script here. So, what I’m going to do is. At the player, okay so if you open the player script. Which is this one.

Instead of instantiating the bullet like this, calling instantiate, we’re going to try to get a bullet from the ObjectPoolingManager. So we want to access the ObjectPoolingManager, but how do we do this? There are two ways. One way is to make the player to reference the ObjectPoolingManager and well, make a direct call for it. But that might be a bit ugly, and that’s not going to be easy to reuse later, because if you make other elements, if you want to pool a particle effect for example, or other bullets and several different things. If you want to access the pooling manager from other places, from the player, from the enemy, from the turret, from the door, whatever elements you have, you need to think of a better way to do this. So we need to make a little mix of the simple return pattern.

So, the ObjectPoolingManager is going to have a reference to the only instance of that pooling manager that is going to be available in the scene. Which is this little guy here. So what I’m going to do here, is type private static ObjectPoolingManager instance, so there’s going to be a reference to the instance of the ObjectPoolingManager. And now, I’m going to type public, then static ObjectPoolingManager Instance, with an uppercase I. I’m going to open and close curly braces, and type get, and, once again, between curly braces, return instance, okay. So it’s a very simple pattern that we’re making for defining a property. If we go the player and we type player. If we type ObjectPoolingManager.instance, we should access the instance that we have here. However, right now it’s going to return null.

So what we can do here is, instead of using start, we can use Awake. And we can type instance equals to this. So, the Awake method happens before the Start method. So we’re going to insure that instance is going to be set once this Awake method is going to be called, okay. And all of the other elements can access it in their Start method, otherwise we have to worry about the script execution order, but let’s worry about that later. Okay, so this is going to be, to make us able to access the ObjectPoolingManager, so as a simple test, I’m going to make here another method, let’s get rid of the update. And it’s going to be public and then GameObject, and let’s name this as GetBullet, for example. We’re going to name it like this. And I’m going to print just a message here. I’m going to type Debug.Log and say hello. And I’m going to type return null. Okay, we’re not going to return any bullets right now. So let’s save this. In the player, just to test it out, I’m going to type ObjectPoolingManager here where we spawn a bullet dot Instance.GetBullet, which is this one here, okay. So let’s see what happens if we do this. I’m going to save, let’s go to Unity. Let’s select the console by the way to see the messages. And now, if we press play, here we are. If I click, I’m printing the hello message. Which means the player is accessing the ObjectPoolingManager without having a direct reference to it. Which is perfect, exactly what we want.

Now, we want the ObjectPoolingManager to be able to access the bullet prefab, to know what the bullet prefab is. So, I’m going to type here, let’s type below these pair of lines, public GameObject bulletPrefab. Okay, so let’s save this, by the way, and go to Unity, wait a little bit, and in the ObjectPoolingManager we’re going to drag and drop the bullet, just like we did with the player. So, prefabs, bullet, drag, drop. Perfect, there we go. And now, what we want to do here, is we want to preload a certain amount of bullets. So I’m going to type public int bulletAmount, and let’s use 20 as default. And here, in the Awake method, we’re going to instantiate 20 bullets, but we’re going to leave them disabled. So, how are we supposed to do this? We’re going to type it like this: for int I equals to zero, while I is lesser than 20, then do something, and finally i++. So, this is a basic loop that’s going to execute 20 times. But instead of using 20 here, we use bulletAmount.

Okay, so you can scale that to whatever you want. And when this happens, we’re going to type GameObject bulletObject, or we can just type here prefabInstance, because we want to make that easier to reuse later, equals to instantiate and then bulletPrefab. Okay, once we do this. Let me, instantiate, there we go bulletPrefab. Once we do this, we also want this bullet to be under the ObjectPoolingManager to keep things organized, otherwise the bullets are going to appear at the root of the Hierarchy. So, prefabInstance. transform.SetParent and we pass transform as a parameter, because it’s going to reference the ObjectPoolingManager. And after we do this, I’m going to type prefabInstance.SetActive and I’m going to pass false as a parameter, okay. So we’re going to instantiate 20 bullets, and all of them are going to be disabled. So this time, if I save this. I go to Unity, and I wait for the processing to be finished.

If we press play, and we look at the Hierarchy, you see that the ObjectPoolingManager has an arrow, because it contains several objects inside it. If you open, you’re going to see the 20 bullets in there sleeping, in their dormant state. Okay, which is good, now we have them. Now, for the getBullet method. What we have to do, is we have to store all of the references for the bullets that we have here somewhere. So we’re going to need a list of bullets. So here, I’m going to type private List of type GameObject and it’s going to be named bullets, simple as that. In the Awake method, before we instantiate the bullets. Let me, let’s add a comment here, so preload bullets. We need to type bullets equals to a new List of GameObject. Okay, that’s a generic list of GameObject. And you can also start by including its capacity. So we already pre-allocate a certain amount of spaces in our memory to load bullets, and the capacity is basically bulletAmount.

Okay, so we’re going to make a new list that can store up to 20 bullets, which is good, okay. And for the getBullet, we have to worry about something, we need to store the references for the bullets, before we try to use the getBullet. So here, when we instantiate the prefabs, I’m going to type bullets.Add, in between parentheses, I’m going to pass prefabInstance, just like that, okay. And if you go to Unity, well you’re not going to see the changes yet, we’re simply going to preload the bullets, they’re going to be stored internally in the list, in a generic list. But now we have to learn how to use them.

Transcript Part 2

We have now set the entire ground work for making the object pooling to fully work. So now we need to go to the object pooling manager, and we have to make the get bullet method to work. And how we’re going to do this, let’s take off these two lines. We want to iterate over all of the prefab instances that we have loaded here, and we need to check if any of them are inactive, because if it is then that’s the bullet that we’re going to use. So to do this, we’re going to type for each game object bullet in bullets. That’s an easy way to make a loop. We’re simply going to check that list for all of the bullets that we have.

Now we check if bullet.activeInHierarchy, this is a property that says basically if the game object is active in the scene. But instead of checking if it’s active, we want to check if it’s inactive. So we add an exclamation mark in the beginning of this statement. So we check if we have anything inactive. If this is the case, then this is the bullet that we want to use. So the first step is we’re going to make it active by typing bullet.SetActive and pass true, as a parameter. So the bullet is going to be back to how it should be. And after that we type return bullet. But there is a problem here. Maybe all of the bullets are being used, so we are going to iterate over all of them. None of them are going to be available because they are all already in the scene. And then we have to return something. If we reach this state, then it means we should instantiate another bullet. So we can just grab the code that we made here for making a new prefab. You can just copy that and paste here.

We’re making a new bullet. There’s only two to use this set active here. So we basically make a new prefab instance. We set its parent to be the object pulling manager, and finally we store it in the bullet’s array, in the bullet’s list. And after we do this, we type return prefab instance. So that’s going to return what we just added. And we’re going to basically add the bullet. And back in the player, instead of using this instantiate method call here, we’re going to use the get bullet from the object pool manager. So I’m going to paste it here. Alright, so now the bullet object is spawned by using the object pooling manager. I’m going to remove the reference for the bullet prefab. The player no longer needs to know what is the exact prefab. And in the bullet there is one important step here.

Instead of calling destroy game object, instead of removing the bullet from the game entirely, we’re going to type GameObject.SetActive false. Otherwise the bullet would disappear after it has been instantiated. And then it would happen over and over again. So we need all of these changes. So let’s test them out. I’m going to save that. Let’s go to Unity. Wait for the compilation to be complete. I’m going to change the bullet amount to two. And I’m going to press play.

So if we go to look at the object pooling manager, we have two bullets. If I shoot one, you see that it got active and then deactivated. But then if I click again, the bullet quickly blinks in the screen. So why is this happening? If you go to the bullet script, you’re going to see that the live timers is only set in the start method. And very important to know is the start method is only called when the object is instantiated. But since this is going to be pooled, we’re going to change the start to OnEnable. So let’s give this a try. We’re going to save this. Let’s go to Unity, wait a little bit more, and we’re going to press play. I’m going to click here, and yes, OnEnable with the case. Now every time I click, the duration is set back to its original state, so the entire lifetime. And take a look at the object pooling manager to see how things are working here.

If I click bullet one is instantiated. If I click twice, both of them are active, because we need two bullets in this case. We’re basically reusing bullets no longer re-instantiating. We’re just retrieving from the pooling manager. If I click several times, new bullets are adding to the pooling manager. So I can click four times very quickly and it’s going to use all of the bullets available.

So basically you can click like crazy, very, very frequently, and the bullets are going to be reused. No more memory allocation, no more very large amount of processing involved in adding these bullets. And now you can pretty much see the limit that you have here. So seven bullets, but let’s change that to eight, just to make sure. So the game is going to have a little time to load in the beginning, but that’s going to save you a lot of time in the future and it’s going to make sure that the game is going to be very efficient.