Select random object from Hierarchy

Hello again I’ve got a crocodile and i want to follow ducks from it. I’ve got DuckSpawner and it creates ducks randomly (3 seconds later, 3.54584 speed ; 4 seconds later 5.75425 speed etc) Their name is “DuckRight (Clone)” so i want to follow one of theese Clones randomly how can i use an array method for this ? Thanks for help :slight_smile:

You can tag them Unity - Manual: Tags ,

Than use GameObject.FindGameObjectsWithTag
Unity - Scripting API: GameObject.FindGameObjectsWithTag, to find your ducks.

For exmaple:

   GameObject[] ducks;
    public float speed = 50;
    void Update()
    {
       ducks = GameObject.FindGameObjectsWithTag("Duck");
       transform.position = Vector3.MoveForward(transfrom.position,ducks[Random.Range(0,ducks.Length)],Time.deltaTime * speed);
    }

But using i dont recomment using Find fuction in Update. I recomment using List. Its very simple and easy;

For example :

Crocodile script;

using UnityEngine;

using System.Collections.Generic;//you need this to use List

public class Crocodile : MonoBehaviour 
{
    public static List<GameObject> ducks = new List<GameObject>();//our List
    public float speed;
  void Update()
  {
      transform.position = Vector3.MoveForward(transform.position,ducks[Random.Range(0,ducks.Length)],speed * Time.deltaTime;    
  }      
}

Duck script;

using UnityEngine;

using System.Collections.Generic;//you need this to use List
public class Duck : MonoBehaviour 
{            
  void Start()
  {
      Crocodile.ducks.Add(gameObject);//Adding us to list;
  }

  void OnDestroy()
  {
          Crocodile.ducks.Remove(gameObject);//Removing us from list;
  }   
}