Pifo
Pifo

Reputation: 77

Get canvas group from parent gameObject

How do I reference canvas groups that are in the Parent gameObject to my array?

public CanvasGroup[] allCanvas;
public GameObject Parent;

public CanvasGroup[] allCanvas;
    // Start is called before the first frame update
    void Start () {
        allCanvas = Parent.FindObjectsOfType<CanvasGroup> (); //this is not working
    }

Upvotes: 0

Views: 378

Answers (1)

Max Play
Max Play

Reputation: 4037

If you want to get all components (CanvasGroup inherits Component) in the parents originating from your source GameObject, you could always use GetComponentsInParent.

An example usage for your case would be

void Start () {
    allCanvas = GetComponentsInParent<CanvasGroup>(true);
}

You should never use any of the "Find" methods if you can find a better way, especially those that return a collection. They iterate over the whole scene graph which can be rather imperformant. Also, if you only want to access the data in parents, then you shouldn't use "Find" anyways, as it does not care about the caller and just returns everything it can find a in a scene.

Upvotes: 1

Related Questions