- Home /
Why is my list empty? (c# question)
I initiate a couple of states and add them to a list like so:
void Start () {
states = new List<GameObject>();
initStates();
}
private void initStates()
{
for (int i = 0; i < numberOfStates; i++)
{
GameObject qf = Instantiate(qfstate, transform.position, Quaternion.identity) as GameObject;
states.Add(qf);
}
}
Then I call some code inside the controller of the newly created GameObject's controller: (This is in another script)
public void measure(){
parent.GetComponent<Parent_Controller>().measure(id);
}
And again back in the original (Parent_Controller) code i have:
public void measure(int id) {
print("in measure!: "+states.Count");
}
And here's the problem: the list is empty! :( I tried the exact same code in the Update() function, like so:
void Update () {
print("in update!:" + states.Count);
}
And here the list is not empty! What's the problem? In the update, the list is definitely filled but in the measure() it is not. The size of the list does not change in the update, it is the same size all the time. I have no idea what is wrong, I would really appreciate help!
EDIT The problem was that I had not passed the information about the parent properly. I had manually set a public GameObject variable "parent" and had linked it as a prefab so the script did not run from the same objects.
$$anonymous$$ake your edit as an answer explaining it a little bit deeply and accept it as you have already found your way.
Answer by Letail · May 29, 2019 at 10:46 AM
I just encountered a similar problem. I was instantiating an object with the script that had the list I wanted to add to.
However, what I was referencing was the prefab reference and not the newly instantiated game object.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Access list storing custom class variables from another script 1 Answer
Is there a way to remove array entries in the editor? 4 Answers
How do I make a list of lists? 2 Answers
Affect every object in array. 1 Answer