How do I synchronise a function called in multiple objects?

Example - I need a bunch of objects to all call a specific function in their script every 5 seconds. I’m thinking using InvokeRepeating.

If all those objects are present at the start of the scene, they start in sync, so they stay that way.

If I create new objects at different times in the game, they’ll be out of sync with each other.

What’s the best way to make them all call that function at the same time every time?

I suggest you using a dedicated class to handle the synchronisation, I’ve called it Repeater. Attach it to an empty gameObject for instance.

using UnityEngine;

public class Repeater : MonoBehaviour
{
    [SerializeField]
    private float interval;

    public UnityEngine.Events.UnityEvent OnRepeat;

    private float timer;
    
    public float Interval
    {
        get { return interval ;}
        set { interval = Mathf.Max( value, 0 ); }
    }

    private void Start()
    {
         timer = Interval;
    }

    private void Update()
    {
        timer -= Time.deltaTime ;
        if( timer < 0 )
        {
            timer += interval ;
            if( OnRepeat != null )
                OnRepeat.Invoke();
        }
    }
}

Then, depending on how you manage your instances, you will have to make those instances subscribe to the OnRepeat event. Here here an example with 2 simple scripts : a Spawner and a Spawnee

// Spawnee.cs    
public class Spawnee : MonoBehaviour
{
    public void SayMyName()
    {
        Debug.Log( name );
    }
}

// Spawner.cs
public class Spawner : MonoBehaviour
{
    // Drag & drop the gameObject holding the Repeater script in the inspector
    public Repeater Repeater;

    private void Spawn()
    {
        Spawnee instance = Instantiate( spawneePrefab ) ;
        Repeater.OnRepeat.AddListener( instance.SayMyName ) ;
    }
}

Thanks for this! I’ve not used event systems before, so this was super helpful.

I altered it a bit, so the spawnee’s prefab adds the listener to itself when it’s created, so both spawned ones and those in the scene when it starts both have it. Totally working now!