- Home /
Referencing prefab in code without using editor or Resources.Load?
I seem to encounter this pattern often, and have not found a clean way to handle it:
I have a MonoBehaviour that instantiates a prefab (e.g. a MonoBehaviour called Fragile that spawns a prefab with a particle system when the object it's attached to is hit). My desire is to avoid referencing the prefab it must spawn in the editor, because then I must manually drag the exact same prefab to the component every single time I add it to an object.
At the moment I'm solving this problem by putting the prefab in a Resources folder, declaring a static GameObject member in my MonoBehaviour, and using Resources.Load in Awake if the member is null. To my knowledge this has the following downsides:
- Once loaded, that prefab is never unloaded since the static reference will remain. 
- Resources.Loadisn't very fast and could result in stuttering if a number of components wake up that all need to load their static references.
 
Other methods I don't think would work well:
- Loading all at startup - this won't scale well. 
- Loading as needed at level load time - the idea of having to track what prefabs are used in a level doesn't thrill me. 
 
Any ideas? I'm relatively new to Unity and I feel there's a gap in my knowledge where the answer lies.
There's also Addressables package that's meant to replace Resources and can be used to load and unload assets at runtime
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                