I need a hand with picking out a random element from a list. I am attempting to spawn prefabs from a list (assigned in the inspector), using a list of Vector3 positions created by several raycasts, I will attach the full script separately as I believe it is not all the relevant.
I am having an issue where the index chosen was out of range (ArgumentOutOfRangeException). I know the random position is the issue, and not the random prefab choice, as the code works if I instantiate at a chosen position.
If I am using lists wrong, please let me know. Any help is appreciated.
void SpawnComponent()
{
for(matchCount = 0; matchCount < numberOfComponents; ++matchCount) //run the loop until the max components has been reached
{
int randomNum = Random.Range(0, spawnPositions.Count);
Vector3 chosenPosition = spawnPositions[randomNum];
Debug.Log(chosenPosition); //for testing
GameObject environmentpiece = Instantiate(environmentPrefabs[Random.Range(0,environmentPrefabs.Count)]/*this works*/,
chosenPosition/*this does not*/, Random.rotation);
}
}
}
full script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateEnvironment : MonoBehaviour
{
public List<GameObject> environmentPrefabs; //list of prefabs to randomly choose from
public List<Vector3> spawnPositions; //holds positions generated by rays
public GameObject centrePoint, thePlanet;
private Collider planetCollider;
public int numberOfComponents = 5; //max components in the scene
int matchCount, matchRay, rayCount = 6;
public LayerMask whatCanBeHit;
void Start()
{
planetCollider = thePlanet.GetComponent<Collider>();
RaycastHit hit;
for (matchRay = 0; matchRay < rayCount; ++matchRay)
{
if(matchRay == 0)
{
if(Physics.Raycast(new Vector3(centrePoint.transform.position.x + 8, 0, 0), centrePoint.transform.position, out hit, 10f, whatCanBeHit))
{
spawnPositions.Add(hit.point);
}
}
else
{
if(Physics.Raycast(new Vector3(centrePoint.transform.position.x - 8, 0, 0), centrePoint.transform.position, out hit, 10f, whatCanBeHit))
{
spawnPositions.Add(hit.point);
}
}
}
}
void Update()
{
if(matchRay == rayCount)
{
SpawnComponent();
++matchRay;
}
}
void SpawnComponent()
{
for(matchCount = 0; matchCount < numberOfComponents; ++matchCount) //run the loop until the max components has been reached
{
int randomNum = Random.Range(0, spawnPositions.Count);
Vector3 chosenPosition = spawnPositions[randomNum];
Debug.Log(chosenPosition); //for testing
GameObject environmentpiece = Instantiate(environmentPrefabs[Random.Range(0,environmentPrefabs.Count)]/*this works*/,
chosenPosition/*this does not*/, Random.rotation);
}
}
}