- Home /
Setting Prefab with Code Returns NULL
Ok I am going crazy how come none of these work? I am trying to make a the GameObject prefab to set to a prefab that I want. So I can later place that block.
prefab = (GameObject)Resources.Load("Objects/Blocks/Dirt") as GameObject;
prefab = (GameObject)GameObject.Instantiate((GameObject)Resources.Load("Objects/Blocks/Snow"));
prefab = Instantiate(Resources.Load("Resources/Blocks/Dirt", typeof(GameObject))) as GameObject;
All return null!
After doing this I then do Instantiate(prefab, G, Quaternion.identity); which works fine but only does it when I drag object to prefab in editor. This can't happen since I need to switch the prefab to other types of blocks.
So what is Dirt? Whatever it is, it's in Resources/Objects/Blocks right or something that looks like that?
Dirt is a Dirt block prefab that is in a folder under Assets/Objects/Blocks
Answer by RudyTheDev · Feb 23, 2014 at 04:27 PM
Because Resources.Load() very specifically says your files have to be in "Resources/" folder.
Also, any reason why are you loading them from resources rather than having a reference to your prefabs from the script? Is it only ever used once?
Its used more than once and I have to be able to switch the type of block i can place on the fly. So I will make a Resources folder and try it.
I hate Resources personally - would suggest an array of prefab references in an object in your scene.
Thanks so much didn't see that in the unity docs thank you. If anyone wants to know this is the code the worked.
prefab = Instantiate(Resources.Load("Dirt", typeof(GameObject))) as GameObject;
Don't forget to place them in a folder you create called Resources :)
@whydoidoit: me too! That's what I always do myself -- make a prefab manager singleton class and keep all my prefab references there. And using Resources
a lot is definitely slower.
And you know your build isn't bloated with a bunch of things you forgot in the Resources folder
Answer by joseques · Feb 23, 2014 at 06:47 AM
Why you dont try to make a List ?
public List<GameObject> mylist;
prefab = (GameObject)Instantiate(mylist[index], G, Quaternion.identity);
Im trying to load different resources based on a set of variables not keep track of each block.
Why are voting negative on my answer? I just only want to help him, I've believed that List could help him...
Your answer
Follow this Question
Related Questions
Simple Looping drag and drop game 1 Answer
Gameobject as Optional Argument 0 Answers
Distribute terrain in zones 3 Answers
I have an error, script should check for null or not destroy game objects 2 Answers