我正在尝试循环遍历卡片对象的2D数组并在Unity场景中实例化它们。但是,在尝试实例化它时,我得到一个Null引用异常。以下是实例化对象的代码:
//Setting up initial board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
//Checked with debug.log, this should work Debug.Log (board[j, i].name);
Debug.Log(board[j, i].name);
temp = Instantiate(board[j,i]) as GameObject;
CardScript cs = temp.GetComponent<CardScript>();
objectBoard[j, i] = cs;
//Setting locations of the cards
objectBoard[j, i].transform.position = new Vector3(30 * j + 20, 50 * i + 70, 0);
}
}
错误发生在'CardScript cs = new ....行中我最初在temp = Instantiate ...行中有错误,当代码是GameObject temp = Instantiate ....它修复了我做的时候在代码中临时一个私有的GameObject变量。我不认为我能用这个做到这一点,因为我需要引用我正在实例化的每个单独的对象。
完整代码:
public class MatchScript : MonoBehaviour {
public CardScript[] potentialCards;
private CardScript[,] board;
private CardScript[,] objectBoard;
private List<CardScript> entries;
private GameObject temp;
// Use this for initialization
void Start () {
entries = new List<CardScript> ();
objectBoard = new CardScript[4,3];
board = new CardScript[4, 3];
foreach (CardScript c in potentialCards)
entries.Add (c);
foreach (CardScript c in potentialCards)
entries.Add (c);
//Loading up the board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
int k = Random.Range(0, entries.Count);
board[j, i] = entries[k];
entries.RemoveAt(k);
}
}
//Setting up initial board
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++){
//Checked with debug.log, this should work Debug.Log (board[j, i].name);
Debug.Log(board[j, i].name);
temp = Instantiate(board[j,i]) as GameObject;
CardScript cs = temp.GetComponent<CardScript>();
objectBoard[j, i] = cs;
//Setting locations of the cards
objectBoard[j, i].transform.position = new Vector3(30 * j + 20, 50 * i + 70, 0);
}
}
}
// Update is called once per frame
void Update () {
}
答案 0 :(得分:1)
我不确定为什么会这样。但你可以通过改变来解决这个问题
temp = Instantiate(board[j,i]) as GameObject;
到
temp = Instantiate(board[j,i].gameObject) as GameObject;
答案 1 :(得分:1)
“expression as Type”子句将表达式强制转换为Type当且仅当实际类型的表达式派生自Type时,否则返回null。
Instantiate生成一个传递的对象的独立副本,当然,它具有CardScript类型。现在,存在一些可能的误解:GameObject是Unity场景中所有“实体”的基类,但不包括您自己创建的所有类。如果CardScript是您创建的类,并且它没有显式继承任何类,那么它将继承System.Object(它是所有 C#类的基类)。
如果CardScript派生自GameObject,那么你也应该提供该类。