I have a 2D array of gameObjects pieces
. When I want to rescale them in my private void ScalePieces()
method, I get a NullReferenceException. If I instead just use Debug.Log() I dont get an Error. This is the whole code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PieceDrawer : MonoBehaviour
{
public string[,] BoardArray = new string[8, 8];
public GameObject[,] pieces = new GameObject[8, 8];
private bool setup = false;
public float scale = 0.7f;
private (int, int) WhiteKing = (0, 0);
private (int, int) BlackKing = (0, 0);
public GameObject bishopBlack, bishopWhite, kingBlack, kingWhite, knightBlack, knightWhite;
public GameObject pawnBlack, pawnWhite, queenBlack, queenWhite, rookBlack, rookWhite;
private Dictionary<string, GameObject> PrefabPiece = new Dictionary<string, GameObject>();
public string fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
void Start()
{
PrefabPiece["b_b"] = bishopBlack;
PrefabPiece["b_w"] = bishopWhite;
PrefabPiece["k_b"] = kingBlack;
PrefabPiece["k_w"] = kingWhite;
PrefabPiece["n_b"] = knightBlack;
PrefabPiece["n_w"] = knightWhite;
PrefabPiece["p_b"] = pawnBlack;
PrefabPiece["p_w"] = pawnWhite;
PrefabPiece["q_b"] = queenBlack;
PrefabPiece["q_w"] = queenWhite;
PrefabPiece["r_b"] = rookBlack;
PrefabPiece["r_w"] = rookWhite;
}
private void Update()
{
if (fen != "" && !setup)
{
SetupPieces();
setup = true;
}
}
private void SetupPieces()
{
var x = 0;
var y = 0;
var fenList = fen.Split();
foreach (var position in fenList[0])
{
if (position == '/')
{
x = 0;
y++;
}
else if (char.IsDigit(position))
{
for (int i = 0; i < (position - '0'); i++)
{
BoardArray[x + i, y] = " ";
}
x += position - '0';
}
else
{
switch (position)
{
case 'k':
BlackKing = (x, y);
break;
case 'K':
WhiteKing = (x, y);
break;
}
var clr = char.IsUpper(position) ? "_w" : "_b";
BoardArray[x, y] = position.ToString().ToLower() + clr;
x++;
}
}
DrawPieces();
}
private void DrawPieces()
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
if (BoardArray[x, y] != " ")
{
pieces[x, y] = Instantiate (PrefabPiece[BoardArray[x, y]], new Vector3 (x, y, 0), Quaternion.identity);
pieces[x, y].GetComponent<SpriteRenderer>().sortingOrder = 1;
ScalePieces();
}
}
}
}
private void ScalePieces()
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
// Debug.Log("Hello");
Vector3 scaleVec = new Vector3(scale, scale, 1);
pieces[x, y].transform.localScale = scaleVec;
}
}
}
}
And the error message I get in unity:
NullReferenceException: Object reference not set to an instance of an object
PieceDrawer.ScalePieces () (at Assets/PieceDrawer.cs:118)
PieceDrawer.DrawPieces () (at Assets/PieceDrawer.cs:104)
PieceDrawer.SetupPieces () (at Assets/PieceDrawer.cs:91)
PieceDrawer.Update () (at Assets/PieceDrawer.cs:44)
As I said changing the method to something else fixes the error, so I think it definetly has to do with transform.localScale
. I also tried calling the method from other methods; same error.