Creating lasers in Unity
For today’s article, I’ll be going over how I let the player shoot lasers using the space bar.
Goals
- Have the laser spawn above the player
- Have the laser spawn above the player when pressing space bar
- Apply upward velocity to laser when spawned
Spawning Lasers
In Unity, there is a built-in function called Instantiate that allows the Player
script to spawn projectiles or lasers. The arguments or parameters Instantiate takes in are the prefab game object, starting location (Vector3), and starting rotation (Quaternion).
The SerializeField
attribute enables Unity to serialize the GameObject laserPrefab
which gets exposed in the Unity Editor in the Inspector tab when the Player GameObject is selected. laserOffset
is a Vector3 that applies an offset to where the laser should be spawned at. In my use case, I apply an offset that is 0.8 units in the y direction from the player.
What is a Prefab?
A prefab is a file that is saved typically in the Prefabs
folder that is used to spawn GameObjects during runtime (e.g. runtime = enabling play mode in the Unity Editor). Prefabs can be thought of as a template that contains components with preset variables that the instantiated game object will use the first time it is visible in the game world.
Spawning Lasers when space bar is pressed
In the above code, the laser gets fired whenever the space bar key is pressed and is called inside of the Update() function.
Applying upward velocity when a laser is spawned
In the Laser
script, I use the transform.Translate
function to apply an upward velocity inside of the Update function. This allows the laser to move on every tick for X units per second where X is the speed variable set.
Thanks for reading!