How to Make an Object Follow Another in Unity (MoveTowards Tutorial)

Опубликовано: 17 Март 2026
на канале: DevSpark
482
16

In this Unity tutorial, I’ll show you how to use the MoveTowards method to make one object track and move toward another. This is a simple and effective way to create enemy AI, homing projectiles, or following mechanics in your game

SCRIPT:

using UnityEngine;

public class ProjectileBehavior : MonoBehaviour
{
[SerializeField]
private float speed = 5f;

[SerializeField] Transform player;
private Vector3 playerPosition;

void Start()
{
playerPosition = player.transform.position;
}

void Update()
{
MoveToPlayer();
DestroyOnHit();
}

private void MoveToPlayer()
{
transform.position = Vector3.MoveTowards(transform.position, playerPosition, (speed * Time.deltaTime));
}

private void DestroyOnHit()
{
if (transform.position == playerPosition)
{
Destroy(gameObject);
}
}
}