Unity-实例化新对象时为空引用

本文关键字:引用 对象 实例化 新对象 Unity- | 更新日期: 2023-09-27 18:26:13

我正在尝试循环遍历卡对象的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=Instantate中出现错误。。。行,当代码为GameObject temp=实例化…时。。。。它修复了我在代码中使temp成为私有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 () {
}

Unity-实例化新对象时为空引用

我真的不确定为什么会发生这种情况。但您可以通过更改来解决此问题

temp = Instantiate(board[j,i]) as GameObject;

temp = Instantiate(board[j,i].gameObject) as GameObject;

"expressionasType"子句将表达式强制转换为Type,当且仅当表达式的实际类型派生自Type时,否则返回null。

实例化生成传递的对象的独立副本,该对象自然具有CardScript类型。现在,有一些可能的误解:GameObject是所有"Unity场景中的实体"的基类,但这并不包括你自己创建的所有类。如果CardScript是您创建的一个类,并且它没有显式继承任何类,那么它继承System.Object(它是所有C#类的基类)。

如果CardScript是从GameObject派生的,那么您可能也应该提供该类。