0
votes

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!

1
what error is it returning? Please post that as well as your instantiate coderyeMoss
What is ai (how is it defined)?UnholySheep
@UnholySheep List<GameObject> ai. You can tell by by looking at ai.Count and ai.Add(obj);. @OP Your question is not clear and you are not even instantiating anything.Programmer
@Programmer it might just as well be List<Object> or ArrayList or a bunch of other containers (or even something custom that just happens to implement the Count property and Add method) - IMO it's a rather important detail to knowUnholySheep
@Programmer my apologies, I just reverted that not to instantiate things. I'm gonna update the code a bit.SkildX

1 Answers

2
votes

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