Instantiating a prefab as a component type?

I’m confused by the ability to instantiate an object as a component type, like a Rigidbody. For example, take Unity’s own instantiate tutorial here:

It’s the standard “instantiate a rocket when you fire” example. It makes perfect sense to me that your rocket would be a prefab of a gameobject with attached components like rigidbody, collider, etc. But I don’t understand what you’re doing when you instantiate a prefab and cast it into a Rigidbody. How is that cloned object different than just a gameobject with a rigidbody attached?

That tutorial basically explains that instantiate returns a type called “object”, and that even if the prefab you’re instantiating has a Rigidbody component attached, your cloned object will NOT “be” a rigidbody. Makes no sense to me. I instantiate prefabs as just GameObjects all the time and they act exactly like they should with the components already attached to the prefab.

The short answer is: Because that’s the way Unity and method Instantiate() was designed to work internally.

If you play with the Instantiate a bit, you notice that when you’re instantiating from a Rigidbody, you always get a Rigidbody, and a GameObject from a GameObject.

In the Unity Instantiate tutorial you’re referring to, they are instantiating from a Rigidbody, and in that case Instantiate returns a Rigidbody.

All the basic building blocks you attach to your GameObjects in Unity, Rigidbody, Colliders, Joints… extend the class UnityEngine.Component which in turn extends the class UnityEngine.Object. Since Instantiate can clone any Object, it can logically also clone any Component. When it is used to clone a Component, it clones the GameObject the component was attached to too, and all other Components that were attached to the GameObject.

The reason Instantiate returns a Rigidbody when you clone from a Rigidbody and a GameObject when you clone a GameObject is simply because that’s how it was designed.

They could’ve also “overloaded” the Instantiate method for each subclass of Object too but they decided to make just one method that can clone and return any subclass of Object and leave the casting to the right type to us users.

The way I understand it, you’re simply working with the RigidBody component of a GameObject. I believe the structure is always a GameObject containing components such as Transform and RigidyBody. You’ll see the same thing with the Transform component. People often use Transform instead of GameObject to Instantiate or link if that’s the data they will be using on the GameObject.

From the Instantiate reference:

If you are cloning a Component then the GameObject is[sic] is attached to will also be cloned, again with an optional position and rotation.