Search Unity

Picking X random objects in a list

Discussion in 'Scripting' started by Sushin, May 16, 2015.

  1. Sushin

    Sushin

    Joined:
    May 2, 2015
    Posts:
    25
    Hi guys. I'm trying to solve what I imagine to be a simple problem but I'm not sure how to go about it from a psuedo code standpoint.

    Basically, I have X spawners, and I want to spawn in Y (smaller than X) things at the start of the game, randomly, all in the position of different spawners.
    So I want to randomly choose Y out of X spawners to create objects at, if that makes sense.

    Can anyone help me out? C# preferred.
     
  2. Crayz

    Crayz

    Joined:
    Mar 17, 2014
    Posts:
    193
    One way to do it would be to create an empty game object titled something such as "Spawn Points", give it some child empty game objects each placed where you want your spawn points to be. Then you could do something like this:

    Code (csharp):
    1. // Amount of things to spawn
    2. int y = 5;
    3. // Array containing all the spawn point transforms
    4. Transform[] spawnPoints = GameObject.Find("Spawn Points").GetComponentsInChildren<Transform>();
    5.  
    6. void SpawnThings()
    7. {
    8.    // Execute a for loop to spawn y amount of things
    9.    for(int x = 0; x < y; x++)
    10.    {
    11.      Vector3 spawnPosition = spawnPoints[Random.Range(0, spawnPoints.Length-1)].position;
    12.  
    13.      // Instantiate here using spawnPosition
    14.    }
    15. }
     
  3. Sushin

    Sushin

    Joined:
    May 2, 2015
    Posts:
    25
    Thank you!
    It seems to work, though they can spawn in the same place twice (which I believe I can fix easily) though I approached it in a slightly different way.

    Code (csharp):
    1.         GameObject[] gos;
    2.         gos = GameObject.FindGameObjectsWithTag ("Spawner");
    3.  
    4.         for (int x = 0; x < Total; x++) {
    5.             Vector3 spawnPosition = gos[Random.Range(0, gos.Length-1)].transform.position;
    6.             Debug.Log("Spawning At: " + spawnPosition);
    7.         }
     
  4. mweldon

    mweldon

    Joined:
    Apr 19, 2010
    Posts:
    109
    Look up a technique called Reservoir Sampling. Google it. It is how you pick a X elements from a group of Y elements with no repeats.
     
    Jamez0r likes this.