Search code examples
unity-game-engineunityscript

Spawning several random objects in several random positions only when a scene begins


I want spawning several random objects in several random positions only when a scene begins. How can I do it? This is my code, but only appears one object.

using UnityEngine;
using System.Collections;

public class SpawnItems : MonoBehaviour
{
    public Transform[] SpawnPoints;
    public GameObject[] Objetos;

    void Start () 
    {
        int spawnindex = Random.Range (0, SpawnPoints.Length);
        int objectindex = Random.Range (0, Objetos.Length);

        Instantiate (Objetos [objectindex], SpawnPoints [spawnindex].position, SpawnPoints [spawnindex].rotation);
    }

}

Solution

  • I made a function to do exactly this for a game I'm working on.

    public List<GameObject> spawnPositions;
    public List<GameObject> spawnObjects;   
    
    void Start()
    {
        SpawnObjects();
    }
    
    void SpawnObjects()
    {
        foreach(GameObject spawnPosition in spawnPositions)
        {
            int selection = Random.Range(0, spawnObjects.Count);
            Instantiate(spawnObjects[selection], spawnPosition.transform.position, spawnPosition.transform.rotation);
        }
    }
    

    The way it works is you place your different locations in a list, and all of the different prefabs of objects you want to spawn in a separate list, then the loop spawns a random object at each of the different positions.

    Remember to put:

    using System.Collections.Generic;
    

    At the top of the class in order to use Lists. You could also use Arrays for this, but I personally prefer lists.

    And the Start() function is only ever called once per object, so this code will only run once each time the scene is loaded.