- Home /
Creating Prefabs at runtime?
How can I create a Prefab object within the code without having to assign a Prefab to a public variable of a MonoBehaviour class?
I know I could declare a public variable in a class, drag the Prefab to the variable, and then call Instantiate to create the Prefab object within the code. However, without having a variable assigned to a Prefab at compile time, can I still instantiate a Prefab object from the Assets folder within my script at runtime?
Answer by Bunny83 · Jan 09, 2013 at 09:13 AM
Yes, but only if it's placed in a Resources folder. You have to use Resources.Load to get the reference to the asset.
Keep in mind that Unity will always include all assets in the Resources folders since Unity can't determine which ones you will use. Also those assets are always loaded before the start scene. It's usually always better to reference the used assets from a manager script in a scene.
If you have a lot prefabs you could write a small editor script which helps you to assign them.
Thanks for the answer. And +1 for the suggestion! Thanks! I don't quite understand the part where you said "It's usually always better to reference the used assets from a manager script in a scene." Could you elaborate a little more on this? What is meant by an "used asset"?
Your answer
Follow this Question
Related Questions
Dictionary Keys to Stack Enemy Types 1 Answer
Call a function in an instanciated prefab has no effect on the prefab 2 Answers
Instantiated prefab doesn't collide with player 0 Answers
instantiate prefabs y+1 from last instintiated prefab 1 Answer
Trying to instantiate prefabs to a parent object with C# script. 1 Answer