Finding gameObjects and adding to a list

A while ago I posted up a thread about Random Map Generation, I’d created something I liked but it was very basic so I’ve decided to go over and re-code the whole thing. I need to be able to access GameObjects easily and to reduce lag I decided to add them to a List instead of searching each time.

Initially I’m running this to test with before cleaning it up, but the issue I’m having is there should be two gameObjects with the Script “Connector” that has a boolean set to false called isUsed. But it’s only finding and listing one of them, before this is called I instantiate the first room that only has one connector. Could this be why? I thought setting a List to a new List<> reset the size of it?

GameObject[] foundConnectors = GameObject.FindGameObjectsWithTag("Connector");
        foreach(GameObject c in foundConnectors) {
            Connectors = new List<GameObject> { };
            Connectors.Add(c);
        }

foreach(GameObject c in Connectors) {
            if(c.GetComponent<Connector>().isUsed) {
                Connectors.Remove(c);
            }
        }

EDIT: Nevermind, as soon as I posted the code I realized what I’d messed up with so just in-case anyone has a similar issue take a look at the code below, it’s essentially the same as above.

GameObject[] foundConnectors = GameObject.FindGameObjectsWithTag("Connector");
        Connectors = new List<GameObject> { };

        foreach(GameObject c in foundConnectors) {
            if(!c.GetComponent<Connector>().isUsed) {
                Connectors.Add(c);
            }
        }

i think the problem is that both Objects have the Name “Something(Clone)”. evt. Try to Rename the Objekts when they are spawning. Something1 … Something 2 …

Thanks for the reply, it wasn’t that as I was using Tags the issue was that I was running List = new for each time I ran the Add command, so I was always ending up with one GameObject. I just had to place this above the Foreach statement and clean the code up.

1 Like