预制件已成功实例化,但在访问时,在Unity中生成NullReferenceException

时间:2016-01-17 08:41:32

标签: c# unity3d

我有一个预制件的初始化:

GameObject e = Instantiate(entry, new Vector3(x, y, 0), Quaternion.identity) as GameObject;

我知道它已成功实例化,因为我可以在层次结构中看到克隆。但是,如果我尝试访问它,则会出现NullReferenceException。我试过这个:

Debug.Log(e.ToString());

而且:

e.transform.SetParent (GameObject.Find("Canvas").transform);

但是它显示了这个错误

  

NullReferenceException:未将对象引用设置为的实例   object StudentListController.FillList(System.String strList)(at   资产/脚本/ StudentListController.cs:45)   StudentListController + c__Iterator5.MoveNext()(at   资产/脚本/ StudentListController.cs:23)

这是FillList的代码:

void FillList(string strList) {
    string[] studentData;
    string[] studentList = strList.Split (';');
    int startX = -253;
    int startY = 70;
    int addX = 100;
    int addY = 30;
    for (int y = 0; y<studentList.Length; y++ ) {
        string student = studentList[y];
        studentData = student.Split(',');
        for(int x = 0; x<studentData.Length; x++) {
            string data = studentData[x];
            if (x==3) {
                data = getAgeFromBirthdate(data).ToString();
            } else if (x==4) {
                data = getSex(data).ToString();
            } 
            GameObject e = Instantiate(entry, new Vector3(startX + 100*x, startY + 40*y, 0), Quaternion.identity) as GameObject;
            //e.GetComponent<Text> ().text = data;
            //e.transform.SetParent (GameObject.Find("Canvas").transform);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

检查您是否在预制件的自定义组件中拖放了所需的任何内容。如果您拖放它们,则应单击“应用”。