How does instantiate connect to rigidbody?,How does instantiate userigidbody without getcomponent?

I been studying c# and unity a lot more lately i mostly been off and on but now im serious, and stuck.

I been following tutorials on cgcookie and im confused around the start function. why is it unessacry? i can comment out the GetComponent and it works just fine but how?
the best idea for why is that it finds the component a other way in the update function.

But im not sure how or what exacly makes GetComponent unnessacry?

Im still new to c# & unity so i wont be able to understand anything to advanced sry!

I am slighty aware clone is a Rigidbody type but im not sure how it connects to the component of Rigidbody is it the “as rigidbody” part?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cannonball : MonoBehaviour {
public Rigidbody projectile;
public int throwPower;
// Use this for initialization

void Start () {
//projectile = projectile.GetComponent ();
// Update is called once per frame

void Update () {
if(Input.GetButtonDown(“Fire1”)) {
Rigidbody clone = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection (Vector3.forward * throwPower);


If you want to know about the scene the object the script is connected to is a empty game object and the script shoots a ball prefab from it. I dont want to show any screen shots of the scene for respects for cgcookie.

This code would only work if projectile has a value assigned in the inspector. Likely the tutorial had you “drag and drop” some prefab from your Assets folder to wherever you have this script in your scene. When you drag and drop your prefab on, it assigns the Rigidbody from that prefab to the projectile member of your cannonball class instance when the game is started. This means that projectile has a value at run time. This also means your code in Start() is not necessary. Actually, it wouldn’t even work if you hadn’t assigned projectile in the inspector since you need projectile to have a value before you can call GetComponent on it. (It is also redundant to call GetComponent on a Component when the Component you want is that one lol) If you ran this without assigning projectile in the inspector you would get an error thrown. Probably an “object reference is not set to an instance of an object” error. (And another error if you didn’t have your code in Start() commented out)

In the Instantiate call below, you are instantiating a GameObject based on a Rigidbody component. This means Instantiate will return to you a Rigidbody component attached to the GameObject it creates. You are then assigning that Rigidbody to clone. Then you are setting the velocity of clone to move it.

(Personally, I don’t like Instantiating GameObjects based on a Component, but it is valid to do so.)

Hope this helps!! :smiley: