unity input system

Unity Input System: FREE Tutorial #3 Unity Multiplayer Game

Unity 3D MMO Tutorial Series

Welcome to Unity Input System: Unity MMO Game Tutorial #3. If you have not completed the second tutorial, go back and finish it. You can find the tutorial Coding In C# here. If you are looking for the first tutorial, you can find it here. This tutorial will start the inner workings to get the character moving with the code. We will add code to the “PlayerControls.cs” script.

There is, however, a tiny bit of housekeeping I want you to do first. Create a new ” Model ” folder in the “Player” folder. Drag the “LowPolyMan” icon next to it into the “Model” folder. Next, create a folder called “Prefabs” in the “Player” folder.

Here is what the “Player” hierarchy should look like:

unity input system
Player Hierarchy

From the Hierarchy tab, drag the “Player” or whatever you named your player character into the “Prefabs” folder. You will be asked if you want a “Prefab Variant” or “Original Prefab.” Choose “Original Prefab.”

unity input system
Original Prefab

You have just created your first prefab in Unity! If you are wondering what a prefab is exactly, drag the prefab out onto the “Scene” tab. It is a duplicate of the “Player,” just a different instance. While using a new “Player” instance, you could alter it to be an enemy or even another player character! When finished, you may delete the new “Player” instance from the “Hierarchy” tab.

unity input system
Instanced Player Character

Creating The Unity Input System From Scratch!

Open up the “PlayerControls.cs” script and add a new variable under “public BaseControls baseControls;”:

public Vector2 inputs;

NOTE: Always remember to save your code after adding a new code! The code will NOT reflect in the Unity editor unless the file is saved.

Let’s examine the code. “public” means you may call the variable from anywhere. If you wrote the code to be “private,” only the PlayerControls class could access it. Also, in Unity, “public” will serialize the variable and show Inputs X and Y in the “Player Controls (Script)” in the Inspector tab.

unity input system
Inputs Serialized

“Vector2” allows us to give two input types (x, y). X and Y are axis points that we need to plot the location of the “Player.” “Inputs” is the variable name.

Next, create a C# method, “GetInputs,” under the Update method. A method is a block of statements in a program’s code. The method is called, and any needed method inputs are specified, which causes our statements to be performed. Every command in C# is executed inside the context of a method. Here is the exact way to code this:

void GetInputs()
{
}

What Does It Mean?

What is void? Void is the return type. “Void” means the method returns no values. However, If the method were to make a calculation and return an integer value such as 1, you could write “int GetInputs()” instead of void, for instance.

Now we put something inside the curly braces to make this method work. Let’s make an “if” statement. An “if” statement is a conditional statement that reads, “if the player presses the W key, then do whatever the method is supposed to do.” So, type the following into your “GetInputs” method:

void GetInputs()
{
    if (Input.GetKey(baseControls.forward)) 
    {
        inputs.y = 1; 
    }
}

This “if” statement reads: “If the key is pressed and held down (in this case, it’s the W key), move the Player forward by one.”

The “Input.GetKey” is a Unity method that gets the specified key. “baseControls.forward” is passed in from the BaseControls.cs script.

With one more line of code, you will see the effects of what we have done so far. In the “Update” method, we will call our “GetInputs” method.

 void Update()
 {
     GetInputs();
 }

This statement will call the “GetInputs” method we just wrote. The “Update” method is called by Unity once every frame. As a result, “GetInputs()” will also be called once every frame. While pressing the W key, the Player will move forward by 1 in the Y axis once every frame with the proper code.

Press Play

We can check if our script is working by saving the script and clicking the play button in Unity. With the game running, press the W key. Look for Inputs X and Y in “Player Controls (Script)” in the Inspector tab.

unity input system
Y is 1

Notice the Y value is 1. If you release the W key, the Y value remains at 1 since you have not written any code to change the Y value back to zero. We will fix that in a bit.

We will add the code to move backward for the next part. Inside the “GetInputs()” method, add the following lines of code:

 if (Input.GetKey(baseControls.backward)) 
 {
     if (Input.GetKey(baseControls.forward)) 
     {
         inputs.y = 0; 
     }
     else
     {
         inputs.y = -1; 
     }
 }

The main ‘if” statement does the same as the “if” statement for the forward movement. However, the Y axis in the inputs statement is negative 1. Notice what is called an “if else” statement. This statement reads: “If the W key is pressed AND the S key is pressed simultaneously, inputs.y equals zero. Meaning, of course, the player doesn’t move. We added this code to avoid conflicts when both buttons are pressed.

The “else” statement reads: “if the W key isn’t pressed, but the S key is inputs.y = -1.” Or, in other words, move the player backward 1. If you run the game and look in the Inspector, you will notice that inputs.y is -1 when you press the S key.

No Buttons Pressed

Let’s add one more code block along with our forward and backward inputs. Type the following code at the bottom of the “void GetInputs()” method, and I will explain what is going on:

if ((!Input.GetKey(baseControls.forward)) && !Input.GetKey(baseControls.backward))
{
     inputs.y = 0;
}

This code block will check to see if neither of the keys, W or S, is being pressed. The “!” symbol means NOT, so it would read, “if the W key is NOT pressed AND the S key is NOT pressed, then the character doesn’t move.” The “&&” means AND.

The Code So Far In Unity Input System

Hopefully, your code matches the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
    public BaseControls baseControls;
    public Vector2 inputs;
    void Start()
    {
        
    }
    void Update()
    {
        GetInputs();
    }
    void GetInputs()
    {
        if (Input.GetKey(baseControls.forward)) 
        {
            inputs.y = 1; 
        }
        if (Input.GetKey(baseControls.backward)) 
        {
            if (Input.GetKey(baseControls.forward)) 
            {
                inputs.y = 0; 
            }
            else
            {
                inputs.y = -1; 
            }
        }
        if ((!Input.GetKey(baseControls.forward)) && !Input.GetKey(baseControls.backward))
        {
            inputs.y = 0;
        }
    }
}

Save your script using the ctrl + S keys (cmd + S on Mac). Press play to make sure your code runs. Check your code against the above code if you have any compiler errors. You can read more about keyboard API here.

The next tutorial will add the strafing and rotation controls to the code. Soon the character will be moving! Leave a comment if you like this tutorial series!

Until next time, May The Force Be With You, Always. – Dragon

Tagged

Leave a Reply

Your email address will not be published. Required fields are marked *