Menu Close

Simple Character Movement in Unity with C#

Step 1: Create a new Unity 3D Project.

Step 2: Create a Plane from the GameObject menu.

Step 3: Create a Capsule from the GameObject menu.
You may need to resize the Capsule to fit the Scene.

Step 4: You may want to change the position of the Camera.

Step 5:
a. Select Capsule in the Scene menu.
b. Then go to the Inspector window and click Add Component.
c. Then search “new script” and click new script.

Step 6: Name the new script to player_movement and the click the “Create and Add” button.

Step 7: Left click the 3 dots to the far right of player_movement (Script) and then click “Edit Script”.

Step 8: Inside you script editor, type and save the code as shown below.

using UnityEngine;

public class player_movement : MonoBehaviour
{
    private Rigidbody myplayer;
    Vector3 playerPosition;
    
    void Start()
    {
       myplayer = GetComponent<Rigidbody>();
    }


    void Update()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 3.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
        transform.Translate(x,0,z);

    }

        void fixedUpdate()
    {
        playerPosition = myplayer.transform.position;
    }
}

Step 9: Press the Play button and use the arrow keys to move your character.