Welcome to Part 6 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to move an object using keyboard input in Unity. Whether you’re creating a game or another application, moving objects with keyboard input is a great way to add interactivity and control to your scene. For this example we will be using the legacy Input system.
Here’s the code sample:
using UnityEngine;
public class MoveObject : MonoBehaviour { public float speed = 5f;
private void Update() { if (Input.GetKey(KeyCode.RightArrow)) { transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f); }
if (Input.GetKey(KeyCode.LeftArrow)) { transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f); }
if (Input.GetKey(KeyCode.UpArrow)) { transform.position += new Vector3(0f, speed * Time.deltaTime, 0f); }
Turning a passion for video games and software development experience into a focus on video game development and modding. Here you will find How-To's and more.