Reputation: 2711
Is there a way to implement a list of objects of assorted types in C#? I.e.
GenericCollection genCol = new GenericCollection();
Class1 c1 = new Class1();
Class1 c2 = new Class2();
genCol.Add(c1);
genCol.Add(c2);
I'm using this with Unity3D 3 (not Unity3D 4), and I need the collection to be serializable. Here's a description of Unity serializables.
Upvotes: 1
Views: 211
Reputation: 2615
No, Unity does not support polymorphic serialization directly at all.
You will need to find an alternative design that does not require this feature. Keeping a separate list for each type is one option:
class MyStuff
{
public List<Class1> Class1List;
public List<Class2> Class2List;
}
You can make a wrapper method to more easily select the list for a type:
List<Type> GetList<Type>()
{
var type = typeof(Type);
if (type == typeof(Class1))
return Class1List;
else if (type == typeof(Class2))
return Class2List;
else
return null;
}
You could write an iterate that would iterate over each item in turn. This is a bad idea as the construction of the iterator will create garbage whihc you should strive to avoid in games with GCes (Unity, HTML5, etc) from experience making games in these platforms.
I don't recall if Unity's version of Mono has generators, but if it does, you can do:
IEnumerable<Object> All()
{
foreach (var i : Class1List)
yield return i;
foreach (var i : Class2List)
yield return i;
}
Without generators, the code is a bit uglier (you will need to maintain your own state), but doable. You should be able to come up with that code yourself. I'd recommend against such approaches in a game if this is meant to be done during play due to the very real problems that garbage collector spikes can have on soft real-time apps like games.
Upvotes: 1