Typing inherited classes into an array of base classes, C#

Hello, my practical knowledge of inheritance is thoroughly lacking and I’ve hit a bit of a roadblock, would like to know how to proceed.

My project’s Main class is tracking an array of planets in a solar system:

public Planet[] planets = new Planet[_pNum];

The way my code is set up at the moment is that Planet is a base class for different planet types, Gas Giants, habitable, whatever. The way I’m trying to instantiate is as follows:

for(int i = 0; i < _pNum; i++)
		{
			if(i <= 1)
				planets *= ScriptableObject.CreateInstance("MP") as Planet;*
  •  	if(i == 2)*
    
  •  	{*
    

_ planets = ScriptableObject.CreateInstance(“Hab”) as Planet;_
* }*

* if(i == 3)*
* {*
* if(0 == Random.Range(0,5))*
_ planets = ScriptableObject.CreateInstance(“Hab”) as Planet;
* else*
* {
planets = ScriptableObject.CreateInstance(“TP”) as Planet;
}
}*_

* if(i < 4)*
_ planets = ScriptableObject.CreateInstance(“GG”) as Planet;_

* if(i < 7)*
_ planets = ScriptableObject.CreateInstance(“IP”) as Planet;
* }*
So far every index in the array is returning null reference exceptions. Is there a way to make my current setup work or is there a correct way of doing this?_

Have you checked whether ScriptableObject.CreateInstance(“XXX”) ever returns an object?

I would imagine that it isn’t correctly constructing the instance, otherwise your code looks ok.

You’d probably be better off doing ScriptableObject.CreateInstance(typeof(MP)) etc. That way you will get a compile time error if the class can’t be found. Avoid using strings if there is a version that is compile time available and you know in advance what you want to create.