Instantiating & Destroying Gameobjects in Unity

This is a simple guide how to instantiate and destroy objects in unity.
To instantiate a gameobject simply means to clone a gameobject and place it in the scene, you also have the option to set it’s position and rotation.
To instantiate the laser being fired from my cube I first created a capsule, added a material and attached a simple laser script that has it moving up as soon as it is instantiated. I then prefabbed this gameobject by dragging into my Prefabs folder in the project view in Unity.
Now for the instantiating part…
In my Player script which is attached to the cube I added a private GameObject variable named _laserPrefab and used the [SerializeField] attribute so I could drag the prefab into the field in the inspector.

I’m using Unity’s Legacy Input System for this example.
When pressing the space key I want the laser to instantiate, so in the Update() method of my Player script I check if the Space key has been pressed and then Instantiate the _laserPrefab using my FireLaser() method.

In my FireLaser() method I instantiate the laser with an offset so that it first appears right above my Cube/Player.
As you can see I use Instantiate, set which prefab to instantiate, set the position I want it to appear and it’s rotation which is no rotation so I use Quaternion.identity.

To destroy the laser when it is outside of the screen view I use Destroy(this.gameObject); as seen in my Laser script below.


Something like this would be much more performant to use Object Pooling which I will cover in a future article. Object pooling will recycle the lasers instead of creating new ones and destroying which creates garbage collection.