Instantiating (such a big word for spawning) and destroying objects. How do I do it? Part 1.

In order for our player to shoot lasers we need to be able to spawn them by using a button; such as the space bar. Also, if we then continue to spawn lasers by continually pressing the space bar, many versions of the laser will be unnecessarily in our scene. We will then need to delete them from the scene.

In order to spawn objects, we first need to make a variable of the object, as below, in the script we want the object to spawn from. In this instance our player script.

Now we can drag the laser prefab from our project folder into the player script, as below.

Now that we have that sorted, what do we want to do? That’s right, when we hit the space bar, we want to spawn a laser. Let’s write that out in pseudo code.

In our player Update() method the code will be:

The result when we run in the Unity editor will be:

As can be seen above, we are spawning a lot of laser clones on top of one another. How can we make them spawn where our player is, and then how do we make them move up the screen? I am sure we will find out soon.