So, the gist of the problem is I am programming with GameObjects in Unity. And I want a function that returns three different objects. The main problem that arises is that two of them are lists of GameObjects and the other is just a single GameObject. What is the best way to fix this issue? Here's my current code as it stands.
static List<GameObject> zombies;
static List<GameObject> humans;
static GameObject psgObject;
public const int HUMAN = 0;
public const int ZOMBIE = 1;
public const int PSG = 2;
public static object GetObject(int @object)
{
switch(@object)
{
case HUMAN:
return humans;
case ZOMBIE:
return zombies;
case PSG:
return psgObject;
default:
Debug.Log("GetObject() method error");
return null;
}
}
The awkward thing about this code is that it requires casting whenever the function is invoked. I tried using dynamic types but the compiler Unity uses doesn't support dynamic typing. What do you recommend in this situation?
Simply turn your single GameObject
into a list then you'll have the same return type for everything, i.e.
public static List<GameObject> GetObject(int @object)
{
switch(@object)
{
case HUMAN:
return humans;
case ZOMBIE:
return zombies;
case PSG:
return new List<GameObject>() { psgObject };
default:
Debug.Log("GetObject() method error");
return null;
}
}
Alternatively change the psgObject
static variable into a list and return it directly.
PS: From a design perspective it would be much better to have different methods GetHumans
, GetZombies
, and GetPSG
since the caller must already be able to distinguish those. And then the question does not even arise.