Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find child objects of parent object by tag?

Tags:

c#

unity3d

for (int i = 0; i < numberOfObjects; i++)
        {            
            if (squadMembers.Length == 0)
                go = Instantiate(squadMemeber);
            Vector3 pos = FormationSquarePositionCalculation(i);
            go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
            go.Rotate(new Vector3(0, -90, 0));
            go.tag = "Squad Member";
            go.transform.parent = gameObject.transform;
            newpos.Add(go.transform.position);
            qua.Add(go.rotation);
        }

I give a tag name "Squad Member" to all the childs but it will tag next time also the object I'm using for the Instantiate the squadMember it self.

So if for example there are 20 numberOfObjects and when somewhere else in the program I'm doing:

squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");

Now I squadMembers will contain 21 objects. But I want it to contain 20. The 20 childs.

like image 846
Dragon Flea Avatar asked Mar 09 '23 03:03

Dragon Flea


1 Answers

You can loop through all the children in the parent gameobject and check to see if the children have the tag you are looking for. If they do, add the gameobject of that child to a list. Your list will then contain the 20 children.

public Gameobject parent;
private List<Gameobject> squadlist = new List<Gameobject>();

    void Start()
    {
          foreach (Transform child in parent.transform)
          {
              if (child.tag == "Squad Member")
                  squadlist.Add(child.gameObject);
          }
    }
like image 122
ryeMoss Avatar answered Mar 18 '23 08:03

ryeMoss