【发布时间】:2021-12-08 22:16:38
【问题描述】:
我做过的课程:
public class singleWeeklyWorking_Period
{ // this class holds a single period of work schedule, that can appear weekly on specific days
public bool[] onDays = new bool[7]; // 7 days a week, set to true on days that this period appears
public int startTime = 0; // in minutes
public int endTime = 0;
public void show() // just for testing
{
UnityEngine.Debug.Log("days: " + onDays[0] + ", "+ onDays[1] + ", "+ onDays[2] + ", "+ onDays[3] + ", "+ onDays[4] + ", "+ onDays[5] + ", "+ onDays[6]);
UnityEngine.Debug.Log("startTime: " + startTime);
UnityEngine.Debug.Log("endTime: " + endTime);
}
}
使用该类的代码(仅用于测试):
public List<singleWeeklyWorking_Period> listOfWeeklyWorkingTime ;
// lists of working time
// Start is called before the first frame update
void Start()
{
singleWeeklyWorking_Period period = new singleWeeklyWorking_Period();
period.onDays[0] = true;
period.startTime = 60;
period.endTime = 120;
listOfWeeklyWorkingTime.Add(period);
listOfWeeklyWorkingTime[0].show();
}
正如您在“singleWeeklyWorking_Period period = new singleWeeklyWorking_Period();”中看到的。我实例化了这个类。但它仍然给我一个错误,上面写着:
NullReferenceException:对象引用未设置为对象的实例
它是类中的变量吗?但我在将其添加到列表之前已设置它:
period.onDays[0] = true;
period.startTime = 60;
period.endTime = 120;
我很困惑,感谢所有帮助!
【问题讨论】:
-
你在创建
listOfWeeklyWorkingTime吗? -
从您显示的代码看来,列表将为空
-
如上所述,您没有实例化列表 (
listOfWeeklyWorkingTime),因此当您尝试.Add该 (null) 列表中的某些内容时,它会引发该异常