I’m looking for a proper solution for the following problem:
My Unity app consists of two main scenes. Lets call them scene A and scene B.
When building the app, there’s a list of prefabs (between 2 and 50 different ones). The user of the app can then choose one of these prefabs to be displayed in scene A or scene B.
Therefore, I need some sort of factory which has the following features:
- Ability to register the various prefabs. Ideally this would be done in a way that allows a person building the app in Unity to simply drag’n’drop the various prefabs into a list shown in the inspector.
- Ability for any scene to request an instance of any prefab.
- Ability to request a preview texture (Texture 2D). Ideally the factory would be able to create a scene, place the prefab in there, grab the texture from the camera and return it as a Texture2D.
- Needs to work in standalone mode (Linux, Windows, MacOS) as well as on Mobile (Android, iOS).
What is the best/recommended way of achieving this?
Given that I need this functionality to be accessible from any scene I assume that I need a static factory class which can be called from any script. However, in that case it seems that there’s no way to use the inspector to simply drag’n’drop the prefabs into a list.
Here’s my factory script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Factory : MonoBehaviour
{
private static List<GameObject> prefabs;
private static List<string> prefabNames;
#if UNITY_EDITOR
static WatchFactory()
{
Initialize();
}
#endif
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
private static void Initialize()
{
// Initialize prefab names
// Ideally we could either assign the names or the prefabs directly in the inspector
prefabNames = new List<string>();
prefabNames.Add("Prefab 01");
prefabNames.Add("Prefab 02");
// Load prefabs
prefabs = new List<GameObject>();
foreach (string prefabName in prefabNames) {
string prefabFullPath = "some/sub/path/within/resource_folder/" + prefabName;
GameObject prefab = Resources.Load<GameObject>(prefabFullPath);
if (prefab)
continue;
GameObject instance = Instantiate(prefab) as GameObject;
if (instance)
continue;
// Hide the instance as we don't want it to show up in the scene
instance.SetActive(false);
// Add to list of prefabs
prefabs.Add(instance);
}
}
public static List<GameObject> models()
{
return prefabs;
}
public static int Count()
{
return prefabs.Count;
}
}
This works well within the unity editor but when building & running on Android the prefabs list is empty.
Any hints are greatly appreciated.