Instantiated Object supposedly null when added to an array

Hi there, this is probably a simple fix but I can’t find a solution

I’m just trying to instantiate a gameobject multiple times into a grid shape using two for loops. When I try to add the instantiated object to a 2d array however, an error is thrown saying the object reference is not set to an instance of an object, despite my Debug.Log(object) clearly displaying the object is there?

public GameObject prefab;
pubic Collider2D[,] Colliders;
public int gridWidth = 6;
public int Gridheight = 8;

void Start()
    {
        for (int x = 0; x < gridWidth; x++)
        {
            for (int y = 0; y < gridHeight; y++)
            {
                Collider2D newCollider = Instantiate(prefab, transform.position + new Vector3(x, y, 0), transform.rotation).GetComponent<Collider2D>();
                Debug.Log(newCollider);
                Colliders[x, y] = (BoxCollider2D)newCollider;
            }
        }
        Debug.Log(Colliders);
    }

Any help would be massively appreciated, and any extra info you need I can happily provide. I’ll be active for the next few hours :slight_smile:
9505765--1339291--upload_2023-12-1_20-47-11.png

9505765--1339294--upload_2023-12-1_20-47-27.png

9505765--1339288--upload_2023-12-1_20-46-32.png

Here is the object I’m using as a prefab
9505768--1339303--upload_2023-12-1_20-49-30.png

Then you didn’t find the thing that is null!!

Is it your array? You didn’t post code showing how that gets initialized.

Also it says line 36 but you only posted a small snippet, so go back to line 36 and look again.

Go back to step #1.

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that
1 Like

This was perfect and helped solve my issue, thank you so much.

For any future users, it turns out in my 2D Array definiton I hadn’t defined the dimensions of the array and thus it was just empty, and so when I tried to assign the instantiated objects to a null array things went boom. Thank you again ^u^

1 Like

It’s your array that is null, not the collider.

Edit: Sorry didn’t see that you found the problem.