Search Unity

getting a random object

Discussion in 'Getting Started' started by skeleton-king, Mar 25, 2015.

  1. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    I have parent gameobject which has many child game objects. How do i get a random child game object from those lists of gameobjects.
     
  2. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
  3. proandrius

    proandrius

    Unity Technologies

    Joined:
    Dec 4, 2012
    Posts:
    544
    Code (csharp):
    1. Transform[] childs = gameObject.GetComponentsInChildren<Transform>();
    2. GameObject randomObject = childs[Random.Range(0,childs.Length)];
     
  4. blizzy

    blizzy

    Joined:
    Apr 27, 2014
    Posts:
    775
    I'm not sure just posting the complete solution to a trivial problem is the right approach, that's why I didn't.
     
  5. skeleton-king

    skeleton-king

    Joined:
    Nov 10, 2014
    Posts:
    63
    Cannot implicitly convert type `UnityEngine.Transform[]' to `UnityEngine.GameObject[]'

    I am getting above error when trying above code
     
  6. proandrius

    proandrius

    Unity Technologies

    Joined:
    Dec 4, 2012
    Posts:
    544
    Yeah, here you go:
    Code (csharp):
    1. Transform[] childs = (Transform[]) gameObject.GetComponentsInChildren<Transform>();
    2. GameObject randomObject = (GameObject) ((Transform)childs[Random.Range(0,childs.Length)]).gameObject;
     
    scarletsnake and ow3n like this.