Friday, September 15, 2017

Avoid FindObjectsOfType with this Pattern

public class SomeComponent : MonoBehaviour
{
    public static List<SomeComponent> Instances = new List<SomeComponent>();
    private int instanceIndex = -1;

    void OnDisable() {
        var lastIndex = Instances.Count - 1;
        Instances[instanceIndex] = Instances[lastIndex];
        Instances[instanceIndex].instanceIndex = instanceIndex;
        Instances.RemoveAt(lastIndex);
    }

    void OnEnable()
    {
        Instances.Add(this);
        instanceIndex = Instances.Count - 1;
    }
}

Popular Posts