Creating and removing game objects in Unity using C#

Hal Brooks
3 min readMay 16, 2021

Objective: Instantiate laser pulse when player shoots laser and destroy it when it moves outside the play area.

In Unity, create GameObject > 3D object > capsule and name it Laser. Create a material within the project’s assets and name it Laser_mat, change the aldedo to… say ruby red. Drag the Laser_mat onto the Laser in heirarchy. Create a prefab by moving the Laser into the prefabs folder in your project. Delete the laser in heirarchy. Within the player script, create a private variable for the laser prefab, _laserPrefab, and serialize the field. Save the script and go into Unity to define the prefab by dragging the laser prefab into the open field in the Unity inspector.

Within the player script void Update, use an if statement to monitor for player input, space bar, to fire the laser, provided the laser is not on cool down. This requires a float variable to define the laser rate of fire, _fireRate, and another to monitor the time index, _canFire.

Now the magic happens in FireWeapons() method, shown below. First we set the time index for the cool down timer for the laser by adding the _fireRate to the current timer. The laser is instantiated at the player position plus an offset so that the laser appears in front of the player.

Create a C# script named Laser and attach it to the Laser prefab to allow the laser to move, otherwise the laser pulse just sits where it spawned. Within this new script create a private float variable for laser speed, _speed, which is set to 8f. Within void Update transform.translate moves the laser up by the distance, _speed * Time.deltaTime every frame. An if statement checks to see if the laser has moved outside the play area, and if true destroys the laser to avoid the accumulation of unnecessary game objects.

The player is able to fire lasers when not on cool down and they behave as projectiles, disappearing when they are outside the field of view.

--

--