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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to assign a gameObject to a child gameObject?

Discussion in 'Scripting' started by Caelorum, Apr 2, 2015.

  1. Caelorum

    Caelorum

    Joined:
    Feb 6, 2014
    Posts:
    32
    I'm trying to take a gameobject in a script, and assign it to a gameObject that is childed under a parent.

    Code (CSharp):
    1. void SelectPillar()
    2.     {
    3.         GameObject GO = GameObject.Find("Pillars"+pillarEnemy+"(Clone)");
    4.         int GOChildNum = GO.transform.childCount;
    5.         int randomSpawn = Random.Range (0,GOChildNum);
    6.         goodPillar = GO.transform.Find("Pillar"+randomSpawn+"(Clone)");
    7.     }
    goodPillar is a gameObject, GO is the parent that has already spawned ingame, and "Pillar"+randomSpawn+"(Clone)" is the child.

    I'm getting an error that says I cant assign a gameobject to a transform, but I don't see how the child is a transform. It should just be a gameObject.
     
  2. NeophyteGamer

    NeophyteGamer

    Joined:
    Aug 26, 2013
    Posts:
    38
  3. Caelorum

    Caelorum

    Joined:
    Feb 6, 2014
    Posts:
    32
    Then how am I supposed to access Child GameObjects and manipulate them?

    Edit: Nevermind. Apparently you can create a transform of said child, then access the transform.gameobject.

    Seems like a very complicated way to access a child. But whatever.
     
  4. DRRosen3

    DRRosen3

    Joined:
    Jan 30, 2014
    Posts:
    683
    Code (CSharp):
    1. goodPillar = GO.transform.Find("Pillar"+randomSpawn+"(Clone)").gameObject;
     
    Caelorum likes this.
  5. Caelorum

    Caelorum

    Joined:
    Feb 6, 2014
    Posts:
    32
    That works too, thank you.