Instantiating & Destroying Gameobjects in Unity

Joe

--

Instantiating a gameobject in unity is basically creating clones of a predefined gameobject known in Unity as a Prefab.

For the 2d space shooter the laser that the player shoots will be instantiated. This way the laser asset will only need to be made once, but Unity can use it over and over again as is required.

To do this the following code is used

Instantiate Code

Lets break down what is happening here. The Instantiate() command is what creates all the instances of the laser. But it needs to know some things to do this properly.

First it needs to know what is being instantiated, in this case it is the _laserPrefab which has been created in Unity. Next it needs to know where it is creating this instance of the laser. This is defined with the trasform.position which tells it to create this instance at the gameobjects position. Last it needs to know the rotation of the instantiated object. The laser is not worried about rotation so Quaternion.identity can be used as this quaternion corresponds to “no rotation”.

This will provide the following behavior where the laser is created wherever the player is when the space key is pressed.

Instantiating lasers at player’s position

To make the laser move it will need a script attached to it. The movement will be similar to the process used for the player, except that the laser will only move up. The laser needs a speed and needs to move in real time so the following code will work for the laser movement.

Move the laser up at the defined speed using real time
Lasers that move

The next step is making sure that the laser gameobject does not exist in the game forever, constantly moving upwards until the end of time. This would take up memory and the game would always be keeping track of objects that are no longer valid within the game.

This can be accomplished by finding out the y transform position of the laser after it has left the play area and if it has then using the

Remove a gameobject from the game

This effectively removes the gameobject from the game and frees up the resources that were used in it’s creation and tracking.

The last step is just to clean up the laser and the location it is created. Currently it is generated in the center of the capsule but it would look better if it was generated just ahead of the player. This can be accomplished by using an offset. Find a y offset where the laser is just ahead of the player and use that to instantiate the laser.

First define the offset

Define the laser offset for easy referral later

Then apply the offset variable to the laser instantiation.

Laser instantiated with offset
Cleaner laser instantiation to prevent player clipping

This successfully instantiates a laser where it is wanted and destroys it after it has left the play area.

--

--