//SOLVED Can't add to a class's list from inside a for loop

So I’m a bit perplexed here. Basically, I’m trying to add a position to a List in another class. That class looks like this:

public class TileItems
{
    public string InstanceID;
    public List<ChildObject> ChildObjects;
    public List<Vector3> ChildObjectPositions;
}

And the for loop is pretty simple:

public TileItems tiles;
public void SaveChildTransformData()
    {
        //for each child object
        for (int i = 0; i < transform.childCount; ++i)
        {
            tiles.ChildObjectPositions.Add(transform.GetChild(i).position);
            print("Found child: " + transform.GetChild(i).name);
            foreach (Component comp in transform.GetComponents<Component>())
            {
                childClass.ChildComponents.Add(comp);
            }
            tiles.ChildObjects.Add(childClass);
            //tiles.ChildObjectPositions.Add(transform.GetChild(i).position);
            Debug.Log("Saved child info at position " + transform.GetChild(i).position);
        }
    }

However, the “tiles.ChildObjectPositions.Add etc…” line doesn’t work inside the for loop, but as soon as I put it above the for loop, it works. Also, my for loop is working as the Debug.Logs show in the console.

Why can’t I add to another class’s list in a for loop, and how can I get around this?

If I didn’t explain something, let me know. Thank you for any help!

I managed to get this working by just adding

     public List<Vector3> ChildObjectPositions = new List<Vector3>();

when you declare the list, i think it needs to be initialized (i do this with every collection item e.g. dictionary/list)

Code Below:

    [System.Serializable]
    public class TileItems
    {
        public string InstanceID;
       // public List<ChildObject> ChildObjects;
        public List<Vector3> ChildObjectPositions = new List<Vector3>();
     
    }
    public TileItems tiles;

    void Start()
    {
        SaveChildTransformData();
    }
    public void SaveChildTransformData()
    {
        //for each child object
        for (int i = 0; i < transform.childCount; ++i)
        {
            tiles.ChildObjectPositions.Add(transform.GetChild(i).position);
            print("Found child: " + transform.GetChild(i).name);
            foreach (Component comp in transform.GetComponents<Component>())
            {
               // childClass.ChildComponents.Add(comp);
            }
          //  tiles.ChildObjects.Add(childClass);
            //tiles.ChildObjectPositions.Add(transform.GetChild(i).position);
            Debug.Log("Saved child info at position " + transform.GetChild(i).position);
        }
    }

Result:https://gyazo.com/efc3328af89f73e9277ae56e8d75e773

When you say it “doesn’t work”, is it giving you an error? Or are you just getting different positions in there than you expected?

There’s nothing in C# that forbids you from adding to another class’s list from a for loop; so it’s much more likely you just made a mistake somewhere. You shouldn’t modify a list while looping through that list, but it doesn’t look like that’s what you’re doing, so it wouldn’t apply in this case.

It just doesn’t add anything at all, the list stays empty. No errors.

And Rob’s answer didn’t work for me. Fun times for me…

Are you calling the function anywhere? where is SaveChildTransformData(); being called?

It is being called as my Debug.Logs are firing. I made this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class TestClass1
{
    public List<Vector3> Testing;
}

public class TestList : MonoBehaviour {
    public TestClass1 test;
    // Use this for initialization
    void Start ()
    {
        for (int i = 0; i < 5; i++)
        {
            test.Testing.Add(new Vector3(i, 2, 3));
            Debug.Log("Ran");
        }
    }
}

And even without the “new List…” it works great. So it’s something else in my code; it’s gotten pretty complex.

so your TestClass is working fine? then it might be something wrong with the Foreach loop?

This is the strangest thing I’ve seen in coding. I made a completely different TileItems class (renamed it) and it also doesn’t work, even though the same thing works in another script that I posted above. At this point I’ve commented out everything in the for loop except adding to the class.

Also, I know it’s not being cleared in any way as adding data in the Editor before playing keeps what I wrote in the Inspector; just nothing can be added in the loop.

FINALLY! Found what was wrong. Turns out that because the tile is procedurally generated, I was running that code BEFORE there were any children spawned, so transform.childCount was 0. ANOTHER tile had spawned children, and IT was spamming the console, but I was looking at the Inspector of the tile that ran the code before any children were spawned. Also, I learned that Awake is run regardless if a script is enabled or disabled, so that caused issues for me too.

So I was looking in the wrong place all along. Anyways, thanks for trying to help; sorry for wasting your time on something that wasn’t an issue.

1 Like