[SOLVED] Object reference not set to an instance - using Instantiate().

Thanks for reading!
I am trying to instantiate a random object from a GameObject array.
Whenever the Instantiation happens, I get an error saying:
NullReferenceException: Object reference not set to an instance of an object

The line im getting the error at, is this:

void RoomInstantiation(){
        instantiatedRoom = Instantiate(dungeonRoomPrefabs[assignedRoomNumber], transform.position, Quaternion.identity, gridObject.transform);
    }

at the start of the script i have assigned dungeonRoomPrefabs like this:
public GameObject[ ] dungeonRoomPrefabs

assignedRoomNumber is a random number between 0, and the length of dungeonRoomPrefabs.

Why do I get an error? Please help me out here :frowning:

gridObject may also be null

I’ve checked, its not.

Are all the dungeonRoomPrefabs elements assigned?

PS
In situations like this, when there is a couple of reasons for null reference exception in one line, split that line into several ones:

var prefab = dungeonRoomPrefabs[assignedRoomNumber];
var gridTransform = gridObject.transform;
haveinstantiatedRoom = Instantiate(prefab, transform.position, Quaternion.identity, gridTransform);

If the error is still at the Instantiate line, then prefab is null.

PPS
There’s also a possibility that some field (dungeonRoomPrefabs or gridObject in your case) is assigned in the inspector, but when you start the scene it gets overwritten by your own code somewhere in Start or Awake or even some other scripts. So, the initial values get lost at the runtime and you get nulls or other values instead.

All the elements are assigned: Script - Album on Imgur

I’ll try your solution, and let you know how it goes.

Holy moly. I’m very embarrased right now. Turns out the gridObject was indeed null. Thank you so much for the help. It wasn’t for nothing. This isn’t the first time im getting the
Object reference not set to an instance
error.

Next time, I’ll make sure to put it into different lines to figure out which line causes the problem.