How do I access components in a prefab via script? (C# / Unity)

In my Unity project, I have a prefab that’s a panel with two buttons (and their text) and several text fields. How do I access those text fields and change them via script? All the examples I find are for prefabs that have only a single component of a given type, like only one text field, or only one image, and they’re grabbed with GetComponent. I tried this, but I’m getting a null result.

newObj = (GameObject)Instantiate(prefabPlayerPanel, transform);
var buttons = newObj.GetComponents();

I thought this would give me an array of the two buttons in the prefab. I tried the same approach to grabbing the text fields, also with null result. What am I doing wrong?

GetComponents only returns components that are on that GameObject specifically. If you want to get the Buttons that are children of the panel, use GetComponentsInChildren.

1 Like

Yes, that’s what I needed. Thanks!