Skip to main content
2 of 7
added 63 characters in body
Philipp
  • 121.5k
  • 28
  • 261
  • 342

You just have to make the other characters do exactly the same things the player-character does, but with a delay. So you have to create a script which records the position of the player and then allows to retrieve the player's position X steps ago.

The C# standard already has the ideal data-structure for that, the Queue. It allows you to create a first-in-first-out buffer of a fixed size where you can add elements to the end with Enqueue and remove elements from the beginning with Dequeue.

using System.Collections.Generic;
using UnityEngine;

public class FollowTheLeader : MonoBehaviour {
    public GameObject leader; // the game object to follow - assign in inspector
    public int steps; // number of steps to stay behind - assign in inspector

    private Queue<Vector3> record = new Queue<Vector3>();
    private Vector3 lastRecord;

    void FixedUpdate() {
        // record position of leader
        if (lastRecord != leader.transform.position) {
            lastRecord = leader.transform.position;
            record.Enqueue(lastRecord);
        }
        // remove last position from the record and use it for our own
        if (record.Count > steps) {
            this.transform.position = record.Dequeue();
        }
    }
}

This script is just a very simple proof-of-concept. It only copies the position, but you likely also want it to copy the player's rotation (or at least the direction it faces), what action it performs (walking, jumping, etc.) and also handle a couple other edge cases specific to your game. So you will likely need to record more in the queue than just a Vector3. If that is the case, create your own struct with all the data you need and use that as the type of your queue.

Philipp
  • 121.5k
  • 28
  • 261
  • 342