x


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[i] = ScriptableObject.CreateInstance("MP") as Planet;

         if(i == 2)
         {
          planets[i] = ScriptableObject.CreateInstance("Hab") as Planet;
         }

         if(i == 3)
         {
          if(0 == Random.Range(0,5))
              planets[i] = ScriptableObject.CreateInstance("Hab") as Planet;
          else
          {
              planets[i] = ScriptableObject.CreateInstance("TP") as Planet;
          }
         }

         if(i < 4)
          planets[i] = ScriptableObject.CreateInstance("GG") as Planet;

         if(i < 7)
          planets[i] = 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?

more ▼

asked May 19 '12 at 09:38 PM

Gennadios gravatar image

Gennadios
11 3 7 8

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered May 21 '12 at 08:32 AM

whydoidoit gravatar image

whydoidoit
33.1k 12 23 101

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x4179
x138

asked: May 19 '12 at 09:38 PM

Seen: 447 times

Last Updated: May 21 '12 at 08:33 AM