Unity recipes – follow object

The following C# script for Unity can be used to make an object follow another. It can be used, for example, to make a camera follow the player.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour {

   public GameObject player;

    private Vector3 offset;

    void Start ()
        offset = transform.position - player.transform.position;
    void LateUpdate ()
        transform.position = player.transform.position + offset;


In the case of a camera follow, this script should be attached to the camera. A reference to the object to follow (player) should then be dragged into the Player slot in the Unity editor.

LateUpdate is used because it is guaranteed to run after all items have been processed in Update and we know absolutely the player has moved for the given frame. The offset is used to maintain whatever distance is set between the objects.