Create and Destroy

MattGomez
3 min readNov 10, 2022

--

A simple projectile function using Instantiate and Destroy.

Often in games we create and destroy objects during gameplay. This can be done a number of ways, but a quick and easy way is to use Unity’s “Instantiate” and “Destroy” methods alongside prefab objects.

In this article, we will be using these methods in the context of a twin stick shooter to fire bullets from a player cube object.

To start, we need to create a projectile “prefab,” which is a game object template that we can reference later. First, we create a 3D capsule object within the heirarchy. Then we reduce its x, y, and z scales to 0.2. We can then create an object material to change it to a more fitting color, in this case we’ll go with a light blue.

A simple bullet object.

Now, in order to create the bullet in the scene when the player fires, we will need to write some code within the player’s Update method. First we want to know when the player presses the fire key, in this case the spacebar. We can do this easily with Unity’s legacy input system alongside an if statement.

Now we need to actually create the bullet when the player presses space. This is done using Unity’s Instantiate method, which creates an object at a specified location. To do this we simply create a reference to the projectile prefab, call the Instantiate method in our if statement, and specify our player’s position.

We additionally use “Quaternion.identity” which is just simple way to tell Unity not to rotate the object.

We use SerializeField to set the prefab reference in Unity’s editor.

Now we need to program the projectile to move up the screen and delete itself, as not to overload the program with a bunch of objects.

For this, we create a new “Projectile” script, and use transform.Translate to have it constantly move up. We can then create a simple bounds variable, and tell the object to use the Destroy method on itself when it hits that boundary.

We again use SerializeField variables to let us make quick changes in the Unity editor.

We can now press spacebar in our game to fire simple bullets! This method can be used for a number of other functions as well, such as sword slashes and destructable environments.

--

--

MattGomez

I am a Unity game developer learning with GameDevHQ as well as developing a Card Game. Visit my website: mattgmez98.wixsite.com/matthew-j-gomez