Sure! Here is a simple script that you can use to make a character walk in Unity using C#. This script assumes that you have a character controller component attached to your character object.
First, let's create a new C# script called "CharacterMovement" and open it in your code editor. Then, add the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float speed = 5.0f; // movement speed of the character
private CharacterController controller; // the character controller component
void Start()
{
// get the character controller component
controller = GetComponent<CharacterController>();
}
void Update()
{
// get input for horizontal and vertical movement
float horizontalMove = Input.GetAxis("Horizontal");
float verticalMove = Input.GetAxis("Vertical");
// create a Vector3 object for the direction we want to move
Vector3 movementDirection = new Vector3(horizontalMove, 0, verticalMove);
// normalize the movement direction vector so we can move at a consistent speed
movementDirection = Vector3.Normalize(movementDirection);
// move the character in the direction we calculated
controller.Move(movementDirection * speed * Time.deltaTime);
}
}
Let me explain how this script works:
- We start by declaring a
speed variable to set the movement speed of the character.
- We then declare a
controller variable to store a reference to the character controller component.
- In the
Start method, we get a reference to the character controller component and store it in the controller variable.
- In the
Update method, we get input for horizontal and vertical movement using the Input.GetAxis method.
- We create a
Vector3 object called movementDirection to store the direction we want to move.
- We normalize the
movementDirection vector so that the character moves at a consistent speed regardless of the input direction.
- Finally, we move the character in the direction we calculated using the
CharacterController.Move method.
To use this script, simply attach it to your character object and adjust the speed variable in the Unity editor to set the movement speed of the character.