I’ve created loads of classes that derive from my base type and there may be more to come. And now i need a list of them all. Is there a simple way I can find them all to populate a Type array? I’ve been trying to find a C# solution. Do i need to use Reflection?
I don’t think thats going to work. I’m not trying to find instanced game objects in the scene.
Allow me to elaborate on what I’m trying to do.
In my game there are robots that the player can program. For every type of behaviour that the player can add to a robot’s program I’ve created a class that inherits from my base class RobotBehaviour. I’ve created loads of these robot behaviour classes and now I want them all in an array so that i can loop through them to display them as options to the player to click on, and then call the constructor of the one the player selects.
Thats the way I’m trying to do it because myBaseType doesn’t derive from MonoBehaviour (i think i should have pointed this out before) so there’s no Awake() or anything like that for each class. But even if there was, I don’t want to collect these types as they’re instantiated for the first time, i want them all from the very start.
I’ve opted to do it manually. Which is not ideal but it works for now.
// in a MonoBehaviour unrelated to myBaseType
public List<Type> typesThatDeriveFromMyBaseType;
void Awake()
{
[INDENT]
typesThatDeriveFromMyBaseType.Add( typeof( newType1 ) );
typesThatDeriveFromMyBaseType.Add( typeof( newType2 ) );
typesThatDeriveFromMyBaseType.Add( typeof( newType3 ) );
...
[/INDENT]
}
You could use reflection. Another mehtod would be to do something isimialr to what you have above, but use a static list.
Create a static List, in your base class. then in the static constructor for each inheriting class, first check if the list is null, if it is create it. Then add your own type to the static list.
static MySubClass {
if (typesThatDeriveFromMyBaseType == null) {
typesThatDeriveFromMyBaseType = new List<Type>();
}
typesThatDeriveFromMyBaseType.Add( typeof( this ) );
}
That way the base class and each subclass can access this single list of all types of the class.