Shooting with Unity’s New Input System
If you haven’t already been following along, I recommend reading part 1 and part 2 of this series first. This will probably make a lot more sense if you do.
So we’ve seen how to use the new Input System to move the player around the screen. Now let’s have the player fire a laser bolt on command. We’ll tie the laser firing to both the Space key and the left mouse button.
First of all, make sure your Input Actions window is open — double-click the GameControl if it’s not.
Setting up the action
Select the Player action map, then click the + at the top of the Actions column to create a new action. Rename the new action to Fire.
Click <No Binding> under the new action. In the Properties column, click the Path drop-down and begin typing “space”. Select Space [Keyboard] when it appears to set it as the binding.
Now click the + next to the Fire action and select Add Binding. Repeat the previous step to set up the new binding, but this time you want to bind Left Button [Mouse] in the Path field.
Your Actions column should now look like this:
Click Save Asset!
Creating a laser
Since we want to fire off a laser bolt every time the action is triggered, we’re going to need to create a prefab — Unity’s way of dealing with reusable objects. Right-click in the hierarchy and create a capsule. Set its position to (0,0,0) and its scale to (0.2,0.2,0.2). Then drag it into the Project window.
The Laser object in the hierarchy should now be blue, indicating that it is a prefab.
Writing the code
Open your Player.cs script. Add the following to the list of variables at the top of the class:
[SerializeField]
private GameObject _laserPrefab;
Putting [SerializeField]
above the variable declaration means that it will be editable in the Unity Inspector while still remaining a private variable. This is safer than making a variable public if you only want to edit it in Unity.
Add the following method after the OnMove()
method:
public void OnFire()
{
Instantiate(_laserPrefab, transform.position, Quaternion.identity);
}
Like when we set up the Move functionality, we’re associating this method with the Fire action by naming it OnFire()
. Unlike last time, we pass no parameters to the method since this is a simple trigger.
When the trigger is activated (by pressing the space key or clicking the left mouse button) we want to create an instance of the laser bolt at the player’s position. At the moment it will just sit there and not do anything, but we can fix that later.
Final step
The last thing we need to do is tell the Player script what prefab it should be instantiating. Drag the prefab from the Project window into the Laser Prefab field on the Player. Make sure you do not drag a copy from the hierarchy — in fact, if you still have a laser in the hierarchy you should delete it now.
Now you can run the game. If you move around while pressing the space key or clicking the left mouse button, you’ll leave a trail of stationery laser bolts.