hi,
need help in a situation where i have to loadall the prefabs from resource folder into an array and then from that array i need to load random prefabs into another array. need to know where i make mistake and also if u can explain me the mistake. thanks in advance.
using UnityEngine;
using System.Collections;
public class spawner_2 : MonoBehaviour {
public GameObject[] prefabPool;
public GameObject[] prefabRandom;
// Use this for initialization
void Start () {
prefabCreation ();
}
// Update is called once per frame
void Update () {
}
public void prefabCreation()
{
prefabPool = Resources.LoadAll<GameObject>("Prefabs");
print (prefabPool.Length);
prefabRandom = prefabPool[Random.Range(0,prefabPool.Length)];
print (prefabRandom.Length);
}
}
Your prefabRandom array is not initialized. You have to initialize it by specifying the size of the array and then add the prefabs to it. Also while adding the prefab to the prefabRandom array you need to specify the index at which you want to add the prefab.
You can intialize prefabRandom array before you use it with:
prefabRandom = new GameObject[3]; // You can replace the 3 with any length you want.
Also you can then add three random prefabs from your prefabPool array into your prefabRandom array like:
for(int i = 0; , < prefabRandom.Length; i++)
{
// We will now add three prefabs from prefabPool to prefabRandom array
prefabRandom *= prefabPool[Random.Range(0, prefabPool.Length)];*
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class spawner_2 : MonoBehaviour {
//you're not initializing anyting with this array.
//[SerializeField] private GameObject[] prefabPool;
//[SerializeField] private GameObject[] prefabRandom;
[SerializeField] List<GameObject> lPrefabPool = new List<GameObject>();
[SerializeField] int n = 10;
void Start ()
{
prefabCreation ();
}
public void prefabCreation()
{
//Logic that will add to your list.
//You need to assign it then add it to a list.
GameObject[] aPrefabs = Resources.LoadAll<GameObject>("Prefabs");
int aPrefabsLength = aPrefabs.Length;
if(aPrefabsLength != 0)
{
foreach (GameObject prefab in aPrefabs)
{
lPrefabPool.Add(prefab);
}
for (int i = 0; i < n; i++)
{
int randomNumber = Random.Range(0, aPrefabsLength);
Instantiate(lPrefabPool[randomNumber], new Vector3(0f, 0f, 0f), Quaternion.identity);
}
}
}
}