Hey guys im trying to create a list of prefabs that i drag and drop in the editor, and then instantiate them in a new list with this code but it doesn’t seem to work, i get heaps of errors. I looked at other answers on the forum and tried them but all of them give me the same error i cant figure out why :S
{
public List<GameObject> prefabs = new List<GameObject>();
public List<GameObject> prefabPool = new List<GameObject>();
public int numberOfPrefabs = 0;
// Use this for initialization
void Start ()
{
for (int i = 0; i < numberOfPrefabs; i++)
{
prefabPool.Add(Instantiate(prefabs) as GameObject);
}
}
The errors i get are
#1' cannot convert System.Collections.Generic.List<UnityEngine.GameObject>' expression to type `UnityEngine.Object'
System.Collections.Generic.List<UnityEngine.GameObject>.Add(UnityEngine.GameObject)' has some invalid arguments
#1' cannot convert `object' expression to type `UnityEngine.GameObject'
The best overloaded method match for UnityEngine.Object.Instantiate(UnityEngine.Object)' has some invalid arguments
Thanks for anyone reading this, i just cant get my head around it
You’re getting this error because you’re trying to feed Instantiate a list of prefabs, and there is no overload that takes as input a whole list. See its documentation at:
Notice that the docs say the first argument, the “original” should be of type “Object”. Now look at what you’re giving it - your variable “prefabs” is of type “List”. Do you understand the error message now? It says it can’t convert the List you gave it to the Object Instantiate expects.
Try this instead:
// Use this for initialization
void Start()
{
for (int i = 0; i < prefabs.Count; i++)
{
prefabPool.Add((GameObject)Instantiate(prefabs*));*
You forgot to index your prefabs list so are instead attempting to pass an entire list to the Instantiate method, which only accepts Object references - like this:
void Start ()
{
for(int i = 0; i < numberOfPrefabs; i++)
{
prefabPool.Add((GameObject)Instantiate(prefabs*));*
} } Also, keep in mind that List exposes its own .Count property that returns the number of items in the list without causing it to enumerate - so keeping a separate numberOfPrefabs counter is unnecessary (just minor FYI, it opens up the possibility of a separate variable being incorrect at some point).