- Home /
Attaching different prefabs via code?
I'm not sure if you can do this but I'm hoping it's possible. I'll use the current example although this isn't exactly what I am doing in game. Basically depending on a certain event (it might be a mouse click or if player hits a certain score or whatever) I want to be able to instantiate different Prefabs into my scene. Normally if I am working with once scene I would do something along the lines of the following:
public gameObject enemy;
....... later in code
private gameObject clone = Instantiate Object off enemy prefab;
I'd then drag the prefab onto the public gameobject in the scene view and things would work fine and I could then interact with "clone" from there on out without dealing with the prefab directly.
However I've run into an issue where I want to spawn a different enemy based on the situation. Lets say I have the following Prefabs in my Heirachy.
Enemy, Enemy_Special, Enemy_SuperSpecial
I'm making them up but go with me. How can I do something like the following?:
//This can be set to null initially that's fine
private gameObject enemy;
public gameObject getEnemy() {
//If certain condition is met pick the appropriate enemytype from the prefabs in my heirachy.
enemy = Whatever GameObject the scripts says is necessary
return enemy;
}
I realise I could add a whole bunch of public gameObjects and add the specific enemies to their respective slots in the inspector but it's probably going to be a little messy that way and I can't guarantee how many objects I'll end up having it could be 3 or it could be 20. Surely I can add a Prefab via code. If so can someone explain in simple terms how I've looked around for ages but just don't understand how to do it.
Answer by aldonaletto · Jan 31, 2013 at 11:28 PM
An alternative to set fields in the Inspector is to load the prefabs with Resources.LoadAll. I've not tested this, but suppose that you should place the enemies in a subfolder of Assets/Resources - say, Assets/Resources/Enemies - then get all of them in an Object array at Start.
Another possibility: save the enemies in Resources and simply load the enemy you want with Resources.Load - for instance:
string enemyType;
if (condition1){
enemyType = "Ogre";
}
else
if (condition2){
enemyType = "Dragon";
}
else
if (condition3){
enemyType = "Skeleton";
}
GameObject clone = Instantiate(Resources.Load(enemyType));
I've upvoted this as I think it will be the most useful but I'll wait until I get home to test that it works, I think this will be the most elegant but I'll work on a similar foundation and post back if I've had to make any changes.
Answer by Duxten · Jan 31, 2013 at 11:29 PM
You can declare an array of Prefabs and instantiate it
var Enemies : GameObject[]; // Array of different Enemies that are used.
var obj : GameObject = Enemies[1]; <--- put inside the [] the number of the enemy you want
Instantiate(obj, pos.position, pos.rotation);
just an example you could make your own changes