Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[Solved] Set tags to children of an instantiated parent

Discussion in 'Scripting' started by kevinkn408, Nov 22, 2019.

  1. kevinkn408

    kevinkn408

    Joined:
    Dec 20, 2018
    Posts:
    4
    Like the title says, I'm trying to figure out how to set the tags of all the children of an instantiated parent object.

    My current code looks like this right now:

    Code (CSharp):
    1. void Shoot() {
    2. var newBullet = Instantiate(bullet, transform.position, transform.rotation);
    3. newBullet.tag = "PlayerBullet";
    4. }
    This is as far as I've got, and it works for giving the parent the tag, but I'm trying to tag all of the children instead. The parent does not need a tag. Thank you :)
     
  2. leftshoe18

    leftshoe18

    Joined:
    Jul 29, 2017
    Posts:
    61
    Code (CSharp):
    1. foreach (Transform t in newBullet.transform)
    2. {
    3.     t.gameObject.tag = "your tag here";
    4. }
    This would only get the parent and the first layer of children. You can make it recursive to get the children of children if you need.
     
    idopongo likes this.
  3. kevinkn408

    kevinkn408

    Joined:
    Dec 20, 2018
    Posts:
    4
    Awesome, works perfectly :) Thank you!
     
    leftshoe18 likes this.