In this lesson, you will learn how to make an object automatically turn to face another target in your 3D environment using the Transform.LookAt method.
Understanding LookAt
Up until now, you have been manually manipulating the transform.rotation property. While that works for fixed angles, it becomes mathematically complex when you want an object to track a moving player or a floating pickup. Unity provides a built-in method called LookAt that handles the trigonometry for you by calculating the exact rotation required to point an object’s "forward" axis toward a specific point in world space.
Implementing the Logic
To use LookAt, you need a reference to the Transform component of your target object. Since you have learned how to use Direct References via Inspector Fields, we will define a public variable to hold that target.
Place this script on your object, then drag your target (like a player) into the slot in the Inspector:
using UnityEngine;
public class TargetFollower : MonoBehaviour
{
// A reference to the object we want to track
public Transform target;
void Update()
{
// Check for a null reference to ensure the target exists
if (target != null)
{
// Point this object's forward axis toward the target's position
transform.LookAt(target);
}
}
}
How it Works
When transform.LookAt(target) is called, Unity performs a calculation to determine the vector between your object's current position and the target's position. It then immediately updates the local rotation so that your object’s Z-axis (the blue arrow in the Scene view) points directly at the target.
Because we placed this inside Update, the rotation is recalculated every frame. This means if the target moves through the World Coordinate System, your object will rotate in real-time to maintain its focus, acting as if it is "tracking" the target. Note that this method rotates the object instantly; for smoother transitions, you would eventually combine this logic with rotation interpolation, but for now, LookAt provides the perfect foundation for target-oriented behavior.
Key Takeaway: The LookAt method is the most efficient way to align an object's forward axis with a target's position in world space without performing complex manual rotation math.