- Home /
Change assigned prefab from script
Hello guys, i want to make a game where the enemies drop random items (armor, weapons etc). So i thought that each enemy should have a script with an empty variable and when he dies a random prefab should be assigned to that variable and be instantiated. Is this possible? Or i should use an other method?
Answer by markpdolby · Nov 08, 2012 at 10:25 AM
You could use Resources.Load(): http://docs.unity3d.com/Documentation/ScriptReference/Resources.Load.html
But I think that would be quite inefficient for what you want to do so I would suggest having a singleton enemy manager class which contains an array of all the items you want to spawn, something like this:
public class EnemyManager : MonoBehaviour{
public static EnemyManager instance;
public GameObject[] items;
void Awake(){
instance = this;
}
public GameObject GetRandomItem()
{
return (items[Random.Range(0, items.Length)];
}
}
and then in the enemy script you would call this function like this:
void Die()
{
Instantiate(EnemyManager.instance.GetRandomItem, transform.position, transform.rotation);
}
So for the GameObject array it should be revealed in the inspector and you just drag all the prefabs you want to use into it. Something along those lines anyway. Hope that helps.
Your answer
Follow this Question
Related Questions
Instantiated object don't recognize MouseClick. 0 Answers
Instantiate A Prefab 1 Answer
Accessing Script on instated prefab 1 Answer
Manipulating a prefab from within the script that instantiated it 3 Answers
Variable not Assigned 1 Answer