C# Instantiate Reference returning null?

Hi. Just a few days into scripting with unity, and this is my first day converting javascript over to C#, so, please bear with me.

I am trying to instantiate a specific object (PrefabCell) which has a script two levels derived from MonoBehavior, and I’m trying to store its reference cast up one level. The object is instantiating just fine - it appears in game and I can interact with it.

Class ReactorMember : MonoBehavior{}

Class ReactorCell : ReactorMember{}

Class ReactorManager : MonoBehavior{
 ...
ReactorMember cell = (ReactorMember )Instantiate( Resources.Load ("PrefabCell"), new Vector3( xpos, 0, zpos), transform.rotation);
cellList.Add( cell );	
cell.transform.Rotate(0,90,0);
...
}

The problem is that the reference variable (cell) comes back null when the instantiation runs, and I get the following error:

InvalidCastException: Cannot cast from source type to destination type.
ReactorManager.Start () (at Assets/Scripts/ReactorManager.cs:36)

And obviously I can’t manipulate the object I just created as a result. I thought it was always viable to cast upwards from a derived class to its parent, but for some reason that doesn’t seem to work here - or I’ve screwed up the syntax in some way I don’t understand.

You need to cast Instantiate as GameObject, not your base class. Things that extend Monobehaviour are components which live on objects, not objects themselves. You Instantiate objects and add components to objects.

Hmm. I see. I was misconstruing the way scripts and objects relate to each other.

I wonder, is there any way to expose the variables and functions in the components of an object so that they can be accessed directly rather than with GetComponent calls? Just for the sake of convenience. I can certainly work with GetComponent if that’s how it should be done.