Move GameObject to another with Speed variation in Unity

It’s a common requirement in games to move GameObject to another. In this article, I am going to share a simple C# script that can help you to Move GameObject to another in Unity. You can attach the following script to your game object which you want to move to another GameObject.

C# Script to Move GameObject to another in Unity

using UnityEngine;

public class PlusOneController : MonoBehaviour
{
    // Adjust the speed.
    public float speed = 1.0f;

    // The target position.
    public Transform target;
    private bool reachedToTarget = false;
    


    void Update()
    {
        if (reachedToTarget)
        {
            return;
        }

        // Move our position a step closer to the target.
        float step = speed * Time.deltaTime; // calculate distance to move
        float distance = Vector3.Distance(transform.position, target.position);
        if (distance < 0.8) // at the end it will slow down to half of its speed
        {
            step = step / 2;
        }
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);

        // Check if the object reached approximately to the target.
        if (distance < 0.001f)
        {
            // Reached to that object
            reachedToTarget = true;

            // Do your Stuff here

        }
    }
}

As you can see in the above C# script, we have 2 public properties, speed & Transform of the target object. So don’t forget to add these 2 values in the Unity Inspector.

This script works in a way that it follows the target object with the speed to specified, but when it reaches nearby it slows down with its half speed. You can remove those lines if you don’t need this speed variation.

You can implement your code at the end where its commented that you can do your stuff. This is the point when your object reaches to the target object.

That’s it.

If you have any questions feel free to ask in the comments section below.

Next

Blink GameObject in Unity

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: