4
votes

I'm very beginner of unity. I wanna instantiate gameObject in script without cloning already existed GameObject by editor. When I saw tutorial in unity3d.com of which code at below, I was curious why rigid body is instantiated.

As I know rigid body is a component of GameObject and child component of GameObject in conceptually. Even though, rigidbody is instantiated only, instance of game object is shown in the scene during playing.

Thanks, in advance.

using UnityEngine;
using System.Collections;

public class UsingInstantiate : MonoBehaviour
{
    public Rigidbody rocketPrefab;
    public Transform barrelEnd;

    void Update ()
    {
        if(Input.GetButtonDown("Fire1"))
        {
            Rigidbody rocketInstance;
            rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
            rocketInstance.AddForce(barrelEnd.forward * 5000);
        }
    }
}
1
Welcome to SO. If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved, and it gives the person that helps you credit for the assist. See here for a full explanation.nwellnhof

1 Answers

5
votes

Quoting from the scripting reference page for Instantiate():

If a game object, component or script instance is passed, Instantiate will clone the entire game object hierarchy, with all children cloned as well.

If you pass a GameObject, it will duplicate that GameObject and return the copy.

If you pass a Component, such as a Rigidbody, it will duplicate the component's GameObject and return the copy's matching component.

Either way, you duplicate the entire GameObject. It's just a question of what return value you'd like. The difference is pretty minor, especially considering you can easily get from one to the other:

GameObject g1 = ...; //some GameObject
Rigidbody r1 = g1.rigidbody;

Rigidbody r2 = ...; //some Rigidbody
GameObject g2 = r2.gameObject;

I suppose the method you're quoting has the advantage of making sure that there is definitely a Rigidbody attached to the rocket.