I’m trying to wrap my head around the relationship between Unity objects and C# classes and types. To illustrate, I have a prefab called PuckPrefab. It has two C# scripts attached as components: FallScriptCS and OtherPropsCS. I also have a manager object called LogistixMgr, that has a single script component called LogistixScript. So the setup looks like this:
PuckPrefab
FallScriptCS
OtherPropsCS
LogistixMgr
LogistixScript
Here’s the subtle and confusing part. LogistixScript has a member variable:
public class LogistixScript : MonoBehaviour {
public FallScriptCS _puckPrefab;
In the Unity editor pane, I drag the PuckPrefab object onto the _puckPrefab field. This seems explicable, in a way: a puckPrefab has a component that is a FallScriptCS; if we think of “having a component” as kinda-sorta like “being a superclass of” then it makes sense why Unity would allow me to map a PuckPrefab object to a variable of type FallScriptCS.
Later, however, I have this bit of code (also in LogistixScript):
FallScriptCS newPuck = Instantiate(_puckPrefab, pos, rot) as FallScriptCS;
What this seems to do is to instantiate an actual PuckPrefab object complete with its FallScriptCS component (as opposed to instantiating just a FallScriptCS object by itself). This is actually what I want it to do, but that’s not the point. The point is: how is the compiler figuring out how to do all of this behind my back? The type that is being instantiated is declares as FallScriptCS; the compiler seems to be saying: “Well, you can’t actually instantiate a script; but the thing to which this particular script is attached happens to be a GameObject, and I’ll instantiate that instead.”
The implication seems to be that if I make a generic container, like:
Dictionary<string, FallScriptCS> pDict = new Dictionary<string, FallScriptCS>();
… and then populate it with the instantiated item:
pDict.add(newPuck)
then what’s getting added is actually a GameObject?
So I guess I’m asking is what is the relationship between a GameObject (like PuckPrefab) having components, and those components being treated (sort of) like descendants in a type hierarchy? What are the rules for type checking and object identity that makes this work?