1
\$\begingroup\$

I want all instances of a prefab to change their velocity when one of them is clicked, and I think having each object constantly check a variable with a coroutine might not be the best solution. How can I reference all instances of the prefab in a script efficiently?

\$\endgroup\$
5
\$\begingroup\$

Gather the instances into a collection as you instantiate them. Then you can iterate over all members of the collection anytime you want, with no search overhead.

public class MyType : MonoBehaviour {

    static List<MyType> allOfMyType = new List<MyType();

    void Awake() {
        allOfMyType.Add(this);
    }

    void OnDestroy() {
        allOfMyType.Remove(this);
    }

    public void DoSomethingToAllOfUs() {
        foreach(var instance in allOfMyType)
            DoSomethingTo(instance);
    }
}
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.