I’m trying to make a class, which holds a few hundred unit types, that can be instantiated with a lookup from other classes. Ideally I’d want it so you could use it like this:
UnitFactory.CreateUnit("GenericUnit");
The problem being I’m struggling to create static lists of GameObjects, without using the resources folder (as I’ve read online that it’s a fair bit slower). What I have right now is this:
[System.Serializable]
public class UnitFactory : RTSBase
{
private static UnitFactory _unitFactory;
[SerializeField] private List<GameObject> units = new List<GameObject>();
public static UnitFactory unitFactory
{
get
{
if(_unitFactory == null)
{
GameObject obj = Resources.Load("UnitFactory") as GameObject;
_unitFactory = obj.GetComponent<UnitFactory>();
}
return _unitFactory;
}
}
public static GameObject CreateUnit(string prefabName)
{
for(int i=0; i < unitFactory.units.Count; i++)
{
if(unitFactory.units[i].name == prefabName)
{
GameObject obj = Instantiate(unitFactory.units[i], Vector3.zero, Quaternion.identity) as GameObject;
return obj;
}
}
return null;
}
}
I get a threading issue from this, saying:
I mean I know I could just make this a singleton and be done with it… but ideally I envisioned a static lookup service, and don’t like to really find workarounds unless it actually isn’t a good idea or not possible.
The problem I’ve encountered is:
- Setting a List as static means you cannot serialize it. So the only way to instantiate GameObjects from this list would be from the Resources folder, which is slower.
- Setting the list as [SerializeField] private List means you need to instantiate the UnitFactory, meaning that I’ll need to either have one in every scene (With a DontDestroyOnLoad).
- I can’t instantiate a prefab with all referenced GameObjects from a static get, as the prefab would need serializing, and a static get, cannot reference a member variable…
Is there a way through this?