- Home /
C# Array of Child Objects
In making an options menu for a game of mine, I've declared a variety of classes to hold each option. There are boolean-, numerical-, text-, colour-slider-, radio-button-, and list-type options. As such, I have classes declared more or less like so (with an enumeration 'opt' to contain the different option types):
public class Option
{
public string title; // The label that appears in a list
public opt type; // The type of option this is
}
public class OptionV : Option // This is for numerical value entry
{
public int digits;
public bool negatable; // Information specific to each type
}
public class OptionL : Option // This type is to contain a list of other options
{
public Option[] list;
public void Push (Option o)
{
// o is added to the list here
}
}
The problem I'm encountering is that I can't for the life of me figure out how to pass these different child types into the OptionL.Push method, or store the different types on OptionL.list. In C++ I know it was as simple as passing around Option pointers, but that doesn't appear to be an option so much anymore.
Answer by Bunny83 · May 04, 2012 at 02:31 AM
Native arrays can't be resized. They need to be recreated with the desired size. However It's better to use a container class like you would do in C++ since you can't resize arrays in c++ either. just import the System.Collection.Generic namespace and use a List:
public List<Option> list = new List<Option>();
Just to prevent you from working into the wrong direction: A lot people recently tried to use custom classes (usual c# classes derived from System.Object) and want them to be serialized in an array or List of the base type. If you just use this at runtime there's no problem, but Unity can't serialize derived classes.
See those questions about that issue: http://answers.unity3d.com/questions/14877/can-a-custom-inspector-serialize-a-list-of-derived.html
http://answers.unity3d.com/questions/245604/does-unity-serialization-support-inheritence.html
Well my push function actually did generate a new array of incremental size, then copied all the elements over, but you're saying the generic list can be resized as simply as calling a built-in push function?
Also, you're saying the Generic List will store the child classes no problem, so long as I do it through code, and not through the inspector, correct?
Alright, it seems the composition approach described in one of those links has made the problem solvable (albeit with a sledgehammer approach). Thanks for the link.