And The Creator Said, “Let there be lasers.”

Christian Fredericksen
3 min readMay 4, 2022

--

Objective: How to instantiate or spawn game objects

No blasphemy here. We ARE the creators of our game and we want lasers to be. So we let them be. And with a few keystrokes we can bring into existence, what previously was not, anything we desire. Not quite like God but, impressive nonetheless.

First off, as usual we need a plan. And we always plan in pseudo code. So, what do we expect to happen?

So, the ‘I’ in this case is the player. We are talking about player behavior and therefore should be in the player script.

Give yourself developer privilege and let’s create a private variable of type GameObject and name it _laserPrefab.

Hop into Unity and notice in the inspector view that the player script now has a spot for the laser prefab we built. Simply drag and drop the laser prefab from the project view into that spot.

Back in Visual Studio, what was the plan?

Right away we see we need an if statement. And we know that hitting the space key is an input…Remember when we wrote this 👇?

What comes next will ring the bells of familiarity. This really shows how Visual Studio’s IntelliCode helps us.

If the player input is is a key press and that key is the space bar…Now we tell it to do something between the {curly braces}. And this is where we instantiate or spawn our laser.

We are Instantiating our (laser prefab, at the player object’s position, with no rotation. That’s what the Quaternion.identity means, no rotation.

CTRL+S(ave) your work, hop back over to Unity and try it out.

SUCCESS!!

Today, we have learned how to include our prefabs into our game and how to instantiate them with user input. In our next article we will cover offsetting our spawn position and adding movement so it looks like we’re shooting lasers and not dropping a trail of breadcrumbs.

Until then, code your imagination to life.

--

--