Games are interactive, right? Players need to be able to interact with the game, and you need to provide feedback to them. In this post I will teach you how to add Unity’s Input system package to your project, and how to use it in your C# script.
Installing the Unity Input system package
To install any Unity package you need to open the package manager. You do that by opening the window drop down menu, then choose package manager. Search for input manager and install it. Follow the prompts on the screen to use the new system. The process will restart your Unity project.
After the project restarts, lets create settings for your input. To do that, open the edit drop down menu, then choose project settings. Select Input System tab on the left, then click on Create Settings Asset. This will create a file that will contain your input systems.
You can learn more about the input system and how to use those settings in Unity’s Input System documentation. The rest of the post will talk about using the default settings and get started as quick as possible.
Using the input system:
In a MonoBehavior class, we should add the package we are using to the top of the class.
Using UnityEngine.InputSystem;
Now we are ready to use classes included in the package, for example Keyboard and Gamepad.
Keyboard input example
To get input from the keyboard, you can create a new Keyboard variable in your MonoBehavior. Then assign the current connected keyboard to it during initializing the MonoBehavior.
public Keyboard _keyboard;
void Start()
{
_keyboard = Keyboard.current;
}
Now, you are ready to detect key presses from the keyboard in the Update method.
void Update()
{
If(_keyboard.wKey.isPressed)
{
//do something
}
}
This will run every frame, and check if the W key on the keyboard is pressed and return true if it was.
The input system is very flexible. I encourage you to read in Unity’s Input System documentation to learn more about how to customize it for your own needs.
Please check our full video covering this topic in our video beginner series for Unity.
Top comments (0)