- Home /
Load multiple instances of a prefab through code
Hello,
I'm trying to load multiple instances of a prefab in my script, it works if I put one instance of the prefab on the scene and assign the variable "playerClone" and then run this code:
public Circle playerClone;
public List<Circle> players;
void Start () {
players = new List<Circle>();
for (int i = 0; i < 10; i++)
{
players.Add((Circle)GameObject.Instantiate(playerClone, new Vector3(i * 1, i * 1, 0), transform.rotation));
}
}
But I don't like to have this dummy instance on my scene I think you can imagine why, after all there is a reason why I wan't to instantiate using code.
I thought I could work around this by using "Resources.Load" so I wrote this code:
public List<Circle> players;
void Start () {
players = new List<Circle>();
for (int i = 0; i < 10; i++)
{
players.Add((Circle)GameObject.Instantiate(Resources.Load("circle"), new Vector3(i * 1, i * 1, 0), transform.rotation));
}
}
Now I don't need the dummy instance anymore, but instead of getting 10 circles there is only one on the screen and also only one in the Hierarchy tab (at run-time, otherwise there are none)
Do you know any way to instantiate multiple prefabs without the need of dummy instances on the scene?
Thanks in advance!
Jelle,
Answer by supernat · Mar 10, 2014 at 09:41 PM
Jelle, unless I misread your question, you want to drag the prefab out of the Project folder (not out of the Scene Hierarchy) and drop it on your playerClone variable in the editor. Otherwise, it is creating a clone of the instance in the scene rather than of the actual prefab.
Nice xD
Thanks a lot,
I still don't get why the Resouces.Load approach results in only one instance tho.
Answer by shawn-wang · Mar 10, 2014 at 10:08 PM
the list item you want to store is type Circle, but the return of GameObject.Instantiate is type GameObject, you have to use GetComponet method of GameObject to get the right type