jdistro07
jdistro07

Reputation: 165

Unity 3D spawning a prefab from a List

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);
    }

The error looks like this

Thanks!

Upvotes: 0

Views: 3947

Answers (1)

ryeMoss
ryeMoss

Reputation: 4343

You are attempting to instantiate a string - you need to instantiate the gameobject in your ai list instead.

Instantiate(ai[indexAI] ,spawn[indexSpawn].transform.position, spawn[indexSpawn].transform.rotation);

Upvotes: 2

Related Questions