If I have many prefabs and I want to instantiate them all, how do I do it without having to rewrite the same code.
I think using a loop then calling Instantiate, but all prefabs are different name, so how can I put them in a list?
for(int i =0; i < size; i++)
Instantiate(prefabName);
You need to create a base class that all your Enemies
inherit from.
public interface Enemy
{
}
Then make all your Enemy prefabs inherit from this.
public class Red_Enemy : MonoBehaviour, Enemy
{
}
Then in the class that spawns Enemies
you can make an array.
public Enemy [] list;
foreach(Enemy e in list)
Instantiate(e);
You can simply populate the list
via the Editor by drag and drop.
You can use a generic name like E1, E2, E3...
for enemies and keep enemy prefabs on a directory such as Prefabs
> Resources
> PrefabName
and then you can use the loop as,
for(int i =0; i < size; i++)
Instantiate(Resources.Load("E"+i), position, rotation);
// "E"+i for E1, E2 ...
Note: Resources.Load()
looks for a path such as Assets/Resources
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.