- Home /
Casting Object to Rigidbody
public Rigidbody projectile;
void Update(){
Rigidbody clone;
clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
}
This is from older Unity documentation (I think now you can leave as Rigidbody out because projectile's type lets the compiler know?). Either way, old or new, I'm still confused as to what's going on. I thought Instantiate() returned an Object. How can this Object be casted to Rigidbody? Any help would be appreciated. Thanks in advance.
Answer by BastianUrbach · Nov 30, 2019 at 10:29 AM
Rigidbody inherits from Component, which inherits from Object. Objects are different from GameObjects. Most "big" things in Unity (Components, GameObjects, Textures, Materials, ...) inherit from UnityEngine.Object. When you instantiate a Component, the entire GameObject that it is attached to is cloned but only the new Component is returned, not the whole GameObject.
In other words,
Instantiate(rigidbody) as Rigidbody
is short for:
(Instantiate(rigidbody.gameObject) as GameObject).GetComponent<Rigidbody>()
Answer by WheresMommy · Nov 30, 2019 at 07:44 AM
I guess, unity is doing some magic behind and instantiating a gameobject with its rigidbody attached, did you check in runtime?