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.