Recording all objects positions so that the player can go back in time and play co-op with themselves

I’m trying to add a feature to a game so that the player can go back in time and play co-op with themselves. To do this I am attempting to store data about every object in memory for around 20 seconds.

To try this out I have made a C# script called TrackerHub and attached this to an object that is the parent of all objects which will be tracked. Then I broadcasted a message with a pointer to the instance of TrackerHub as a parameter. The broadcast then triggered the child class to call a function in TrackerHub which allowed the information to be passed.

I set this up with one object being tracked, only one integer was send as the data to be recorded and the broadcast begin send on the TrackerHub’s update function. However, this caused the game’s FPS to fall from around 70 to 30. Clearly this is not the best way to do it. What would be a better method to use?

Thank you

The best way to do this is to reference either the tracker or the player in the other one, so that the tracker can directly access the players position or the player can directly access the trackers list of positions. Broadcasting is very, very expensive!!! Allways try to reference instead of Broadcast.

Hope this helps
Benproductions1

Like Benproductions1 said, just use direct references to the objects you want to track. Just add a class to every object you want to track. Lets call this class “Trackable”. Now you can easily find all objects which have such a script either with FindObjectsOfType or by going the other way and have each Trackable to register itself to your “Hub” class.

I would go with the second way:

public class Trackable : MonoBehaviour
{
    void OnEnable()
    {
        Tracker.RegisterObject(transform);
    }
    void OnDisable()
    {
        Tracker.UnregisterObject(transform);
    }
}


using System.Collections.Generic;

public class Tracker : MonoBehaviour
{
    public List<Transform> objects = new List<Transform>();
    private static Tracker m_Instance = null;
    void Awake()
    {
        m_Instance = this;
    }
    public static Tracker Instance
    {
        get
        {
            if (m_Instance == null)
                m_Instance = (Tracker)FindObjectOfType(typeof(Tracker));
            return m_Instance;
        }
    }

    public static void RegisterObject(Transform aObj)
    {
        Instance.objects.Add(aObj);
    }
    public static void UnregisterObject(Transform aObj)
    {
        Instance.objects.Remove(aObj);
    }
    void Update()
    {
        // use "objects" to perform your tracking
    }
}