NullReferenceException:调用transform.localScale时,对象引用未设置为对象的实例



我有一个游戏对象pieces的2D数组。当我想在我的private void ScalePieces()方法中重新调整它们时,我得到一个NullReferenceException。如果我只是使用Debug.Log(),我不会得到一个错误。这是整个代码:

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;
}
}
}
}

和我在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)

正如我所说的改变方法到别的东西修复错误,所以我认为它肯定与transform.localScale有关。我还尝试从其他方法调用该方法;同样的错误。

ScalePiecesDrawPieces的循环中调用,当pieces[]的所有表项未设置时。最好在循环结束后调用。

最新更新