Day 5: Let There Be Laser Beams
Today we are going to work through the process of creating a simple laser beam that only generates when we hit the space key.
The very first step is creating an object to represent our laser beam. We’ll start with a simple capsule shape by right clicking in the hierarchy view selecting 3D Object and Capsule.
You can see here I named my new object lazybeam.
Then we will want to position our new object at 0,0,0 and changed it’s scale to 0.2, 0.2,0.2.
Then I created a new material by right clicking on the materials folder in project view and selecting Create and then Material. I simply changed my Albedo (color) to a magenta color so it’s easy to tell my laser beams apart from my player. You will want to name your new material something related to the object you’re going to apply it to.
To create a Prefab folder to store our laser in, right click on assets and create a new folder. Name it Prefabs and then you’ll want to drag your laser beam from hierarchy view down to your prefabs folder. Then you will want to apply your laser material to your laser prefab by dragging and dropping the material up to the object in Hierarchy view.
To apply changes to all instances of the prefab you’ll want to navigate over to the overrides drop down in the inspector.
Click Apply All and now all copies of your laser prefab will look and behave the same way.
How does this look in code? Let’s open up our player script and find out.
We will want to create a new public GameObject and call it laser prefab. Making it public allows us to do this:
Now any time we refer to the laser prefab in our script, it will know we mean our laser prefab.
For convenience we had our laser as a public game object but going forward, this isn’t best practice. We don’t want other objects in the game to be able to change how our laser behaves. So I changed it to private, but put it under SerializeField so we can see it in the Unity inspector. The underscore before laserPrefab is also necessary to indicate this.
For now we will be writing this directly within void Update() because the players movement has nothing to do with the player instantiating(spawning) objects. Later on we’ll be moving this snippet of code to it’s own little segment, but for now let’s break down what it says.
If I push (input) a certain key down (getKeyDown)
and that key is the space key (KeyCode.Space),
the player will spawn (Instantiate) the prefab (_laserPrefab) of our choosing.
This prefab will Instantiate at the current location (transform.position) of our player and the default rotation (Quaternion.identity).
Click save in your editor and then jump back into Unity to see this in action.
We can see that we now create lasers at our current location whenever we hit the space bar.
Pretty cool, huh? Well, tomorrow I’ll be back with another article on how we can make our laser do more stuff.
See you then,