nik
nik

Reputation: 143

Randomly selecting a child object from parent and setting it as active

I'm creating a game in Unity and I'm having some trouble with it. I have 3 different child objects within a parent object, i would like to randomly set 1 of these 3 child objects as the active object and simultaneously disable the other two. I would like this to happen on colliding with another object.

Thanks in advance.

Upvotes: 0

Views: 2247

Answers (2)

user1912771
user1912771

Reputation: 35

I recommend yo to do this instead

public GameObject parentOfChild;

void OnTriggerEnter(Collider thing)
{
    int randomChild = Random.Range(0,2);

    parentOfChild.transform.GetChild(0).gameObject.SetActive(false);
    parentOfChild.transform.GetChild(1).gameObject.SetActive(false);
    parentOfChild.transform.GetChild(2).gameObject.SetActive(false);

    parentOfChild.transform.GetChild(randomChild).gameObject.SetActive(true);
}

Upvotes: 0

trahane
trahane

Reputation: 721

public GameObject parentOfChild;

void OnTriggerEnter(Collider thing)
{

 if("the collision condition")
 {
    int randomChild = Random.Range(0,2);
    if(randomChild == 0)
    {
      parentOfChild.transform.GetChild(0).gameObject.SetActive(true);

      parentOfChild.transform.GetChild(1).gameObject.SetActive(false);

      parentOfChild.transform.GetChild(2).gameObject.SetActive(false);
    }
    else
    if(randomChild == 1)
    {
      parentOfChild.transform.GetChild(0).gameObject.SetActive(false);

      parentOfChild.transform.GetChild(1).gameObject.SetActive(true);

      parentOfChild.transform.GetChild(2).gameObject.SetActive(false);
    }
    else
    if(randomChild == 2)
    {
      parentOfChild.transform.GetChild(0).gameObject.SetActive(false);

      parentOfChild.transform.GetChild(1).gameObject.SetActive(false);

      parentOfChild.transform.GetChild(2).gameObject.SetActive(true);
    }


 }

}

This is considering that all three children are not visible until the collision.It will also work if all three children visible.

In the parentOfChild object pass your gameobject having the 3 children

Upvotes: 1

Related Questions