Move Object in Unity

There are many times that you are going to need to move an object smoothly or use Time.deltaTime. Let’s say we want to move this cube to forward or the Z(Blue) axis.

How To Move Object Smoothly in Unity? What is Time.deltaTime?

To do that Let’s Create a C# script and open it.

  1. The first thing we must do is to create a public float variable for speed and give it a default value like 0.1 .
    public float speed = 0.1f;

2. Write the move code in the Update function.

        this.transform.Translate(0, 0, speed);

3. What this code does is move the object by the value that you give to it.
For example if the object is at the point (X = 5) (Y = 5) (Z = 5)
and use the finction Transform.Tranlate(0, 0, 1) the object’s position will be (X = 5) (Y = 5) (Z = 6)

So with our current code every frame the object will go 0.1 forward

But this code has a problem. Let’s say you create a game and use this code to move an object in your game. everyone has different devices and every device has its own speed and performance and your Game’s FPS( What is FPS ) will be different on different devices. So for example on one device your game will play 38 frames per second and on another device will play 47 frames per second. and your object will move at a different speed. So what is the solution?
Here we use Time.deltaTime
Time.deltaTime is the time between the current frame and the last frame.
You can read unity’s documentation on Time.deltaTime

How we use Time.deltaTime?

To use Time.deltaTime you should multiply your speed with the Time.deltaTime, Like this:

        this.transform.Translate(0, 0, speed * Time.deltaTime);

Before you play your game and test it. you should probably increase the speed variable that we created. 1 or 2 is a good number for a test speed but it depends on your game.

Our final code looks like this.
We probably do not need the Start function.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObject : MonoBehaviour
    public float speed = 1;
    void Start()

    void Update()
        this.transform.Translate(0, 0, speed * Time.deltaTime);

That’s it.
Don’t forget to check our free unity assets
Read more about Unity

Leave a Reply

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