- Home /
how assign prefab from assets to variable
This is my variable to which I can assign one of my 20 prefabs from assets, in order to play a specific animation.
public GameObject _spell;
I would like to assign via script a certain animation. For example, if my player picks up a "spell_Fire" PickUp, I would like Unity to dynamically assign the firespell prefab to my _spell variable.
you could put them in a resource folder and load them in through that..
Resource.Load
Thornekey - since I'm just beginning to code in Unity and C#, I would need a much more detailed help than that.
Ok, sorry. You can have folders called resource folders, and theyre never actually in your scene, just your assets and stuff. you can call them in scripts. so say if you wanted to spawn a mob..
void Start() {
GameObject instance = Instantiate(Resources.Load<GameObject>("$$anonymous$$r$$anonymous$$ob"));
}
do you understand?
You need a folder in your Assets folder called Resources. You than drop your spell prefabs into that folder.
Than from code you can say,
GameObject instance = (GameObject)Instantiate((GameObject)Resources.Load("Spell_01"));
Answer by mclankyman · Mar 11, 2014 at 11:58 AM
You will still need a reference to the spell prefabs using the drag and drop method just so your script knows of them. But you can assign your variables a new type of spell or the different types by instantiating new ones.
Have a look at this documentation.
http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html e.g
public GameObject fireSpell;(assign prefab in inspector)
...
MySpell = Instantiate(fireSpell, transform.position, transform.rotation);
mclankyman - you described how to do something I said I do not want to do. I would like the prefabs to load dynamically, meaning I do not want to assign a prefab manually to the inspector by dragging and dropping. I would like the Player1 to dynamically load FireSpell, when Player 1 walks over a FirePickUp.
Well the first answer is for you then. It should work when using resources. Have you definitely made it a prefab and not just a gameobject? Bare in $$anonymous$$d loading from resources is marginally slower than inspector drag and drop in terms of performance.
but I can't drag 20 different spells into 1 slot in the inspector, am I right? :)
No of course not. But you could drag and drop all 20 types of spells but have 100s of one type of spell.