【问题标题】:My Class is returning null even after instantiating it c# [duplicate]我的类即使在实例化之后也返回 null c# [重复]
【发布时间】: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) 列表中的某些内容时,它会引发该异常

标签: c# list class unity3d


【解决方案1】:

您似乎没有启动列表。

你有这条线。

public List<singleWeeklyWorking_Period> listOfWeeklyWorkingTime ;

改用这个。

public List<singleWeeklyWorking_Period> listOfWeeklyWorkingTime = new List<singleWeeklyWorking_Period>() ;

注意:我假设错误是在您尝试添加对象时发生的。

【讨论】:

  • 对于 Unity 上下文更好的是简单地创建类 [Serializable] public class singleWeeklyWorking_Period { ... } 这样它 a) 可以在 Unity 的 Inspector 中公开和配置 b) 可以保存并且 c) Inspector 将已经自动初始化这个数组作为反序列化的一部分......所以一旦在 Inspector 中配置了所有内容,Start 实际上可以减少到 listOfWeeklyWorkingTime[0].show();
【解决方案2】:

类或结构定义就像一个蓝图,指定类型可以做什么。对象基本上是根据蓝图分配和配置的一块内存。类的实例是使用new 运算符创建的,因此您需要使用它。

 public List<singleWeeklyWorking_Period> listOfWeeklyWorkingTime = new List<singleWeeklyWorking_Period>(); 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 2014-06-30
  • 1970-01-01
相关资源
最近更新 更多