instantiate randomly from one of the three positions

Hi,

I am a pretty noob and it would be great if you help me with this problem. I am trying to instantiate projectiles randomly with an interval from one of three positions.
I get back the error: Object reference not set to an instance of an object.

This is my code:

public GameObject CanonA;
    public GameObject CanonB;
    public GameObject CanonC;
    public GameObject projectile;
    GameObject[] canons;
    int index;
    // Start is called before the first frame update
    void Start()
    {
        canons[1] = CanonA;
        canons[2] = CanonB;
        canons[3] = CanonC;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            index = Random.Range(0, 3);
            Debug.Log(index);
            Debug.Log(canons[index]);
            Instantiate(projectile, canons[index].transform.position, canons[index].transform.rotation);
        }
    }

Hi,
I didn’t understand yet why I received the “Object reference not set…” error, but I found another method that gave me desired result.

public GameObject[] canons;

In case you want to know the reason of that error for future reference, it was because you were trying to add elements to an array which wasn’t initialized. Also, it’s important to remember that when you add elements to an array, the first position of the array starts at the index of 0, not 1.

With that being said, in case your older code was more suited for the project you’re doing, here’s the piece of code I would’ve changed to make it work:

void Start()
    {
        canons = new GameObject[3]; // Initializing the array by giving it a size.
        canons[0] = CanonA; // 0 is the first element of the array, not 1.
        canons[1] = CanonB;
        canons[2] = CanonC;
    }

I hope this helps!!