Code Doesn't work

public void HighlightMoves(List<int> moves)
    {
        for (int i = 0; i < moves.Count; i++)
        {
            Debug.Log(moves[i]);
           
            if (moves[i] % 2 == 0)
            {
                renderers[moves[i]].color = highlightWhite;
            }
            else
            {
                renderers[moves[i]].color = highlightBlack; 
            }
        }
    }

hello, I’m trying to make a chess game but this line of code doesn’t seem to work.

So, this function should change the color of the squares(64) that the player can move his selected piece on.
The list ‘moves’ stores index numbers for the squares that should be highlighted (in this example it stores: 3, 25, 4, 26, 5,27…). The array renderers has all the 64 spriterenderers from the 64 squares stored .
It goes trough every ‘move’ and changes the Spriterenderer.color for that square.

I also let the function display the ‘moves’ at the beginning to check if those are wrong but they aren’t

output:

so the output displays the first 2 moves correctly but then it gives an error that leads to line 59 in my code(renderers[moves*].color = highlightBlack; )*

Well, it’s impossible for us to know what line is line 59 since you only posted a snippet. But the good news is, you already are part way there to figuring out the error since you know what line number it is!

The steps are always the same!

  1. Find out what is null.
  2. Find out why it’s null.
  3. Fix it.

And here is a sticky to help solving null errors in more detail.
https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

1 Like