Search Unity

Spawn Array Help

Discussion in 'Scripting' started by pixelone, Sep 30, 2015.

  1. pixelone

    pixelone

    Joined:
    Apr 16, 2010
    Posts:
    157
    My attempts of what would be a nice little shortcut to scene population if I can get it to work right :(

    1. Spawn multiple objects at random, in random locations.

    I have that part working, but there is a problem.

    PROBLEM:
    Sometimes multiple objects gets spawned in the same location. This is not good. Please help. Here's my code below. I think what I need is to remove spawn points from the array once an item is spawned their.

    Code (CSharp):
    1. public class ObjectsOnTileManager : MonoBehaviour {
    2.  
    3.     public Transform[] points;
    4.     public GameObject[] objects;
    5.  
    6.     void Start(){
    7.         SpawnObjects ();
    8.     }
    9.  
    10.     void SpawnObjects(){
    11.  
    12.         for(int i = 0; i < objects.Length; i++){
    13.      
    14.             int spawnIndex = Random.Range (0, points.Length);
    15.               Instantiate (objects[i], points [spawnIndex].position, points [spawnIndex].rotation);
    16.  
    17.         }
    18.  
    19.     }
    20. }
     
  2. pixelone

    pixelone

    Joined:
    Apr 16, 2010
    Posts:
    157
    Okay I solved my own issue by using a List store my points and objects. I then used:


    The only issue now is, I am getting ArgumentOutOfRange: Argument is out of range
     
  3. pixelone

    pixelone

    Joined:
    Apr 16, 2010
    Posts:
    157
    Code (CSharp):
    1. objects.RemoveAt(spawnIndex);
     
  4. flonch

    flonch

    Joined:
    Aug 20, 2014
    Posts:
    63
    I think the problem is that you're trying to remove list elements at indices greater than the size of the list. For example if there is only one element left in the list, and say the value of the element is 5, then
    Code (CSharp):
    1. objects.RemoveAt(spawnIndex);
    would try to remove the fifth element.

    Try this instead.
    Code (CSharp):
    1. objects.Remove(spawnIndex);