- Home /
How to make an Array equal the Components of an Instantiated GameObject
So I stayed up till 2 last night trying to figure this out. But I only found one other question like mine. This one! The problem is that I am not entirely sure I am implementing their solution correctly. And I have never worked with arrays before so I am learning that as well. This makes troubleshooting difficult because I don't know whether the error is because of my lack of experience with arrays or because of my lack of experience with instantiating. Please help!
private Text[] TextComponentsArray = new Text[1]; //This is me declaring the array
public void FinishButtonClicked () {
NewTerm = Instantiate(TermButton, new Vector2(TermButton.transform.position.x, TermButton.transform.position.y - 500), TermButton.transform.rotation); //Me instantiating a GameObject
TextComponentsArray = NewTerm.GetComponents<Text>(); //Me making the array = all the Text components in the newly instantiated GameObject
Debug.Log(TextComponentsArray[0].text); // Why is array index out of range?
I get no problems up until the Debug.Log line. I am just trying to see if it assigned to the array correctly which apparently it didn't because I am getting the error IndexOutOfRangeException: Array index is out of range
Answer by Bunny83 · Jul 26, 2019 at 04:49 PM
Because there are most likely no Text components on that gameobject. I guess there might be Text components on child gameobjects. GetComponents get a list of components that are directly attached to this gameobject. If you want to find all components including those on children, you have to use GetComponentsInChildren
Your answer
![](https://koobas.hobune.stream/wayback/20220612205547im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
passing multi-dimensional arrays from one script to another? 1 Answer
Unable to randomly instantiate prefab from array 2 Answers
How to access Instantiated GameObject's attached script's values? 1 Answer
Getting a component of an instantiated object returns an error 1 Answer
Instantiating prefab at child (spawnlocations are arrays) 2 Answers