Why is my 2D array outputting null? (all except one spot)
Hey there! My 2D array which stores where each piece is in my chess game is outputting null all except in the final foreach loop. I've tried everything... any advice?
public class BoardManager : MonoBehaviour {
int selectedX= -1, selectedY = -1;
Piece selectedPiece;
[HideInInspector] public List <Piece> activePieces;
public Piece[,] pieces;
void Start(){
this.pieces = new Piece[9, 9];
SetUpBoard ();
foreach (Piece piece in pieces) {
Debug.Log (piece); // this line outputs null
}
}
void SetUpBoard(){
//initialize piece collections
activePieces = FindObjectsOfType <Piece> ().ToList();
//set up piece references
foreach (Piece piece in activePieces) {
//map 2d array coordinates to piece coordinates
pieces [piece.x, piece.y] = piece;
if (pieces [piece.x, piece.y] != null) {
Debug.Log (pieces [piece.x, piece.y]); // this line outputs correctly
}
}
}
}
Answer by CStampGames · Apr 29, 2018 at 02:26 AM
https://git.txstate.edu/C-s449/Shogi/blob/master/Assets/_Scripts/BoardManager.cs here is a link to the full project if that's helpful
I figured it out. The X and Y values passed in were all zero. So I was just overwriting the same spot in the array over and over.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161708im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array 2D of data 1 Answer
[Solved] Array is empty after Scene change.. 1 Answer
Assign values to array elements 1 Answer
How to get a variable value before it was null ? 2 Answers
How to make a 2D array of buttons? 2 Answers