Randomizing a selection from an array

I am trying to randomize the selection of 3 objects that get displayed on a computer, when running either code I am left with the dreaded “Object reference not set to an instance of an object.” the objects are most certainly being found as without the array the items instantiate fine, but with an array I receive this error.

I have tried both this…

    void addSale()
    {
        count++;
        dummyTimer = addTimer;
        rand = Random.Range(0, adArray.Length);
        GameObject temp = Instantiate(adArray[rand], sales.transform);
    }

and this…

    void addSale()
    {
        count++;
        dummyTimer = addTimer;
        GameObject temp = Instantiate(adArray[Random.Range(0, adArray.Length)], sales.transform);
    }

and this…

    void addSale()
    {
        count++;
        dummyTimer = addTimer;
        int arrayLength = adArray.Length;
        rand = Random.Range(0, arrayLength);
        GameObject temp = Instantiate(adArray[rand], sales.transform);
    }

With exact results…

Again. these objects Instantiate fine without an array… meaning that unity can find these objects without fail… untill I add the array, thats when unity can no longer reference the object that is trying to be instantiated, also the count is being added and the timer reset upon receiving the error.

So you’ve narrowed the problem down to the array, and it’s producing a null reference exception. I can’t tell the problem from the code, because I can’t see the array.

Based on what you’ve said, the only suggestion I can really make is that you might not have initialized your array before using it. You must declare an array using the new keyword before you fill or access it. Have you done this?

If the answer is yes, then the array elements must be null. This means that you’re probably not filling the array elements up properly, again, seeing the code for this would be useful to determine this. Since you haven’t, I’d suggest making a foreach loop, go over your array and do a Debug.Log on each element to print the contents. Then you can confirm your array contains what you expect.