GDP 4.2.3 Instantiate

Please Note: The code shown in the video will successfully rotate the cannon around the right axis in the World space but will not work if you rotate the cannon in the scene.

If you want to rotate the cannon in the scene you can fix this by changing the code in the Cannon script from:

void Update()
    {
        float aimInput = Input.GetAxis("Horizontal");
        aimInput *= rotationRate * Time.deltaTime;
        // Rotates the cannon around the right World axis
        transform.Rotate(Vector3.right * aimInput, Space.World);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Fire();
        }
    }

To:

void Update()
    {
        float aimInput = Input.GetAxis("Horizontal");
        aimInput *= rotationRate * Time.deltaTime;
        // Rotate the cannon around the right Local Axis
        transform.Rotate(Vector3.right * aimInput, Space.Self);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            Fire();
        }
    }

Objectives

In this section we're going to learn how to use the Instantiate method to clone and create new GameObjects at runtime. We'll use this to fire new projectiles each time the player presses the space bar.

Instantiation

In computer programming, instantiation is the process of creating a new object or instance from a class. The class acts as a template for that new object.

public class Car
{
    public string model;
    public float speed;
}

Car myNewCar = new Car();

In the Unity Scripting API, we have access to a method called Instantiate which clones a GameObject. We can either clone a GameObject which currently exists in the scene or we can clone a prefab. When we clone a prefab we're essentially creating a new instance as if that prefab was our class template.

public class MyScript : MonoBehaviour
{
    public GameObject prefab;

    void Start()
    {
        // Clones prefab and places new GameObject at the same position and rotation as this GameObject.
        Instantiate(prefab, transform.position, Quaternion.Identity);
    }
}