Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Spawing random object from list

Discussion in 'Scripting' started by steef_qwp, May 30, 2020.

  1. steef_qwp

    steef_qwp

    Joined:
    Mar 20, 2020
    Posts:
    4
    The tile is wrong, it should be array instead of list

    I use this script to spawn random object but is get this error, the objects do spawn but i still get the error

    IndexOutOfRangeException: Index was outside the bounds of the array.
    RandSpawnPoint.Place () (at Assets/RandSpawnPoint.cs:21)
    RandSpawnPoint.Awake () (at Assets/RandSpawnPoint.cs:14)
    UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
    RandSpawnPoint.Place() (at Assets/RandSpawnPoint.cs:21)
    RandSpawnPoint:Awake() (at Assets/RandSpawnPoint.cs:14)​

    i've searched a lot but i couldn't find a solution

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RandSpawnPoint : MonoBehaviour
    6. {
    7.     public Transform mesh;
    8.     public GameObject[] objectsToChoose;
    9.  
    10.     private GameObject placedObj;
    11.  
    12.     private void Awake()
    13.     {
    14.         Place();
    15.     }
    16.  
    17.     private void Place()
    18.     {
    19.         int randIndex = Random.Range(0, objectsToChoose.Length);
    20.  
    21.         placedObj = Instantiate(objectsToChoose[randIndex], transform.position, Quaternion.identity);
    22.         placedObj.transform.parent = mesh.transform;
    23.         Destroy(gameObject);
    24.     }
    25. }
    26.  
     
  2. Ghost2K

    Ghost2K

    Joined:
    Mar 26, 2015
    Posts:
    94
    var ObjectNumber = objectsToChoose.Length-1;
    int randIndex = Random.Range(0, ObjectNumber);
     
  3. steef_qwp

    steef_qwp

    Joined:
    Mar 20, 2020
    Posts:
    4
    Thanks for the reply but only one object of the array is being chosen(if there are two in them)
    I also still get the exeption
     
  4. Ghost2K

    Ghost2K

    Joined:
    Mar 26, 2015
    Posts:
    94
    That's strange. Are there any scrips on your array objects? You can't resize arrays, if there's an object missing, you will get the exeption.

    To instantiate more than one, you have to use a loop, foreach can do this.