Unity: Look at Target Using C#
A simple script to make a game object look at a target in Unity.
Unity: Look at Target Using C#
Learning Unity is so much fun. The Unity Engine has almost everything that you wish there was.
Below is a script which lets an attached game controller
to rotate its transform
so that it looks at the target's transform position
.
using UnityEngine;
using System.Collections;
public class LookAtTarget : MonoBehaviour {
public Transform target;
public float rotationSpeed = 5f;
void Update() {
// Find direction to target
Vector3 direction = target.position - transform.position;
// You might want to delete this line if you want to rotate on all axes
direction.y = 0;
// If we have a direction
if (direction != Vector3.zero) {
// Create rotation towards the direction
Quaternion targetRotation = Quaternion.LookRotation(direction);
// Smoothly rotate towards the target
transform.rotation = Quaternion.Slerp(
transform.rotation,
targetRotation,
rotationSpeed * Time.deltaTime
);
}
}
}
How to Use This Script
- Create a new C# script in Unity named
LookAtTarget.cs
- Copy and paste the code above
- Attach the script to the game object you want to rotate
- Assign a target Transform in the inspector
- Adjust the rotation speed as needed
This script is particularly useful for:
- Camera follow behaviors
- Enemy AI that needs to face the player
- Character head-tracking systems
- Turrets and weapon systems
The Quaternion.Slerp
function provides a smooth rotation instead of an instant snap, creating more natural-looking movement.