我有两个类,genDicTable和StartGame。我想从StartGame中的genDicTable引用一个变量,但它会产生NULL。引用另一个类中的变量会产生NULL
genDicTable.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class genDicTable : MonoBehaviour
{
public TextAsset file;
public double masterCount;
private void Start()
{
Load(file);
masterCount = rowList.Count;
Debug.Log(masterCount); // <-- This properly prints out the value of masterCount
}
public class Row
{
public string id;
public string word;
public string length;
}
public List<Row> rowList = new List<Row>();
public void Load(TextAsset csv) {
// This function assigns a value into RowList
}
}
StartGame.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartGame : MonoBehaviour {
public genDicTable GEN;
private void Start()
{
Debug.Log(GEN.masterCount); // <-- This yields NULL.
}
}
因此,问题是,当我在StartGame.cs访问变量masterCount,它产生一个错误“的NullReferenceException:对象引用未设置为对象的实例。“
我在这里错过了什么?
正如它说的值为空。这种行为没有任何问题。您尚未在startgame.cs中为genDictTable类型的变量GEN创建任何实例 –
请仔细阅读指向的副本。如果你不知道什么是实例以及如何初始化它,那么这里给出的答案都不能帮助你理解你的问题,并且出于同样的原因避免未来的错误 – Steve