Instantiating, Spawning, Objects in Unity with C#…and Then Destroying them
In my previous article I mentioned spawning the Laser from the Player object. Here we will talk more about spawning, or instantiation as well as the process for getting rid of objects that are no longer needed or are no longer in view of the player or the game view.
Instantiation is the way we can create GameObjects from prefabs in Unity. Now, you saw, in the last article, how crazy the linking process looked when put into a list of steps. Here we will cover the details of the process with the how and why added in. The process needs to be studied to be well understood.
The Laser script describes, within itself, that it works with the Laser prefab with the variable _laserPrefab. Linking the Prefab with the script in the Unity editor is the way you get the script to know what it is declaring that it is using (figure a). It would be the same as your house being built, somewhere, and having an address attached to it. But, unless you plop your house on that address, that address is just undefined thing. It’s defined by linking the two together. Think of the address as the script and the house as the prefab. You drop one onto the other to make the reference complete. The same was true of the Player prefab where it declares the same variable as it needs it for ‘Instantiating’ the Laser prefab whenever the spacebar is pressed (figure b).
Now then, destroying game objects is something else that we need to do, especially with the laser. Every time we fire the laser it instantiates the Laser prefab. The prefab then travels upwards in the game view and goes out of sight.
If we allow this to continue, the game will just keep on creating instances of the laser prefab. Even though we cannot see them, they are still there. And their numbers just keep growing until something undesirable happens, where memory failures and performance are concerned.
So, we destroy what is no longer relevant within the game view. We do this in the Laser script.
You quite literally tell your game to “Destroy” the laser. However, you do this by “destroying” the renderer for the laser. We do this with just four lines of code that tell the game to check if the position of the laser on the Y axis equal to or above a predetermined value, in this case 10. If it is then the condition is met and the result is that the script tells the game to stop rendering the object. It looks like this and it is added to the update portion of the laser script.
In the game view and hierarchy, the result is this…
Any lasers going off the screen, and out of view, are now destroyed and no longer pile up in memory.