NullReferenceException

I’ve been trying to make a simple chess game, creating the board via instantiation; however, the code runs but doesn’t actually create any objects. The exact error is like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Board : MonoBehaviour
{
    //Assigning GameObjects and Sprites for instantiation
    public GameObject CellPrefab;

    public Sprite GreenCell;
    public Sprite YellowCell;

    public GameObject PawnPrefab, KnightPrefab, BishopPrefab, RookPrefab, QueenPrefab, KingPrefab;

    public Sprite WhitePawn, WhiteKnight, WhiteBishop, WhiteRook, WhiteQueen, WhiteKing;
    public Sprite BlackPawn, BlackKnight, BlackBishop, BlackRook, BlackQueen, BlackKing;


    public GameObject[,] Squares = new GameObject[8,8];

    //This is the function that will actually draw the chess board
    void Start()
    {
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                //Black Squares have must either have both X and Y coordinates even or both odd
                if (i % 2 != 0 && j % 2 != 0 || i % 2 == 0 && j % 2 == 0)
                {
                    Squares[i,j].GetComponent<SpriteRenderer>().sprite = GreenCell;
                }

                else
                {
                    Squares[i,j].GetComponent<SpriteRenderer>().sprite = YellowCell;
                }
            }
        }
    }
}

Are there Sprite Renderers on the Game Objects inside the Squares array?

Considering you asked a similar question here NullReferenceException

And @LaneFox gave you an idea how to troubleshoot null errors, you should have no issues solving these. Line 31 is your error. What could be null on there?

1 Like

Ah this is older than that one, which I hadn’t seen/realized :slight_smile: Maybe this is resolved. heh.