I made a script where it loads the prefabs from my Resources/ai folder and loop up to five times and generate a random index number. It successfully loaded my prefabs as GameObjects and does generate random index based on the count of the List.
However, I am having trouble upon spawning my prefab to my scene since Instatiate command does return an error while I'm coding.
I have tried methods to grab the name of the prefab through list[index].name
or even list[index].toString()
but it wont work. (Note: list
stands for a variable of a list index
is just an index to grab the game object on the list. This is not the actual code).
How to spawn a loaded GameObject prefab to my scene with a list?
My current code:
public List<GameObject> ai;
public GameObject[] spawn;
int indexAI;
int indexSpawn;
private void Start()
{
var res = Resources.LoadAll<GameObject>("ai/");
foreach (GameObject obj in res)
{
ai.Add(obj);
}
for (int x=0; x<5; x++)
{
indexAI = UnityEngine.Random.Range(0,ai.Count);
indexSpawn = UnityEngine.Random.Range(0, spawn.Length);
string name = ai[indexAI].name;
Debug.Log(name);
//I am currently using this kind of format since this is what I know for now.
Instantiate(name,spawn[indexSpawn].transform.position,spawn[indexSpawn].transform.rotation);
}
Thanks!
instantiate
code – ryeMossai
(how is it defined)? – UnholySheepList<GameObject> ai
. You can tell by by looking atai.Count
andai.Add(obj);
. @OP Your question is not clear and you are not even instantiating anything. – ProgrammerList<Object>
orArrayList
or a bunch of other containers (or even something custom that just happens to implement theCount
property andAdd
method) - IMO it's a rather important detail to know – UnholySheep