Droei
Droei

Reputation: 5

Get a list of all tags in of all child objects in an object

I'm trying to get all tags into a list<string> but it seems that I can only loop through a tags when its a char my best try was using toString()but that also doesn't work.

public List<string> GetWorldObjectsTag()
{
    var worldObjects = new List<string>();

    foreach (string child in worldOBjectsPrefab.gameObject.tag.ToString())
    {
        worldObjects.Add(child);
    }

    return worldObjects;
}
foreach(string name in currentWorldGen.GetWorldObjectsTag())
{
    Debug.Log(name);
    if (name == sawBlade.tag)
    {
        Instantiate(sawBlade, new Vector2(trans.position.x + Camera.main.transform.position.x + 20, trans.position.y), Quaternion.identity);

    }
    else
    {
        Instantiate(testBlock, new Vector2( trans.position.x + Camera.main.transform.position.x + 20, trans.position.y), Quaternion.identity);
    }
}

This might not be a great way of doing it so if anyone has a better idea please tell me.

Edit:

These are the objects I used

picture of materials

Answer I'm able to loop through the transforms and I can revert those transforms back to a gameObject simply by doing transform.gameObject Thanks for the help!

Upvotes: 0

Views: 122

Answers (2)

derHugo
derHugo

Reputation: 90639

In the Unity source code you can see that Transform implements the interface IEnumerable so you can basically do

public List<string> GetWorldObjectsTag()
{
    var listOfTags = new List<string>();

    foreach(Transform child in worldOBjectsPrefab.transform)
    {
        listOfTags.Add(child.name);
    }

    return listOfTags;
}

pretty similar under the hood would be using Linq Select like

public List<string> GetWorldObjectsTag()
{
    return ((IEnumerable<Transform>) worldOBjectsPrefab.transform).Select(child => child.tag).ToList();
}

since it is a type-less IEnumerable in both cases you have to explicitly tell it to use the type Transform.

Upvotes: 0

Christian
Christian

Reputation: 91

I think you can loop through all the child gamebjects using a foreach:

If the above doesn't work then try with Transform:

foreach (Transform child in worldObjectPrefab.transform)
{
    // Here you can access child.tag and add do what you need to do.
}

Sorry but I don't have access to Unity right now. Let me know if this helps.

Upvotes: 2

Related Questions