I was reading through the guide on Assets, Resources and AssetBundles when I came across the following quote about the exception to the rule of not using the Resource folder:
“Examples of this second case include MonoBehaviour singletons used to host prefabs”
What exactly do they mean by this?
I understand it as a GameObject with a script that lets you assign your prefabs so that you can access them programmatically whenever you need.
So the idea would be to load that GameObject (with Resources.Load()) and then access and instantiate the prefabs from it. Does anyone know if that is what they meant/if there is a better way to achieve the same thing?
I would use a ScriptableObject for the same thing, but you can use a prefab as well, I guess.
Here’s the ScriptableObject version:
public class PrefabRegistry : ScriptableObject {
private static PrefabRegistry _instance;
private static PrefabRegistry Instance {
get {
if (_instance == null)
_instance = Resources.Load<PrefabRegistry>("Prefab Registry");
return _instance;
}
}
[SerializeField] private GameObject prefabA;
public static GameObject PrefabA => Instance.prefabA;
[SerializeField] private GameObject prefabB;
public static GameObject PrefabB => Instance.prefabB;
}
// This allows you to instantiate the prefabs like this:
GameObject instanceOfA = Instantiate(PrefabRegistry.PrefabA);
You could do exactly the same thing if PrefabRegistry was a MonoBehaviour attached to a prefab, the only change would be that the type would be declared as MonoBehaviour, and that you’d have to set it to DontDestroyOnLoad,
Note that this design has a downside - loading the Registry makes it, and all the prefabs it references, stay in memory for the lifetime of your application - meaning that if it’s very large, and contains prefabs that you don’t need often, it can become a problem.