Can Static classes have static lists?
So I'm making a debug script so I can have it output into my VR headset and see the log without taking the headset off. This is the script that is managing the log (it is not attached to any gameobject and is just in a folder):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class NDebug {
public static List<string> log;
public static void Log(string content) {
log.Add(content);
}
public static List<string> GetLog() {
return log;
}
}
But when a script tries to call Log
it gives an error:
NullReferenceException: Object reference not set to an instance of an object
NDebug.Log (System.String content) (at Assets/NDebug/NDebug.cs:10)
SeatScript.OnEnable () (at Assets/Scripts/SeatScript.cs:21)
and so this is my question: can static non-instanced lists exist? Is there a way for me to do what I'm trying to do without adding anything to my scene?
Thanks in advance.
Answer by Commoble · Feb 01, 2018 at 05:52 PM
public static List<string> log;
doesn't create a list, it only creates a field to keep a list in. You need to initialize a list and assign it to that field before you can add things to it, e.g.
public static List<string> log = new List<string>();
Ah, thank you. I'm so used to being able to do things like Vector3 v;
to create an empty vector3 and such that I just assumed it would do the same with the list. Thanks for your help.
The very very short version of why this works this way is that every field and variable you declare initializes to some default value; but structs are value types (like primitive ints and floats) and they generally initialize with a useable default value (ints and floats default to 0). Classes are reference types, and variables of reference types default to null. (Technically they default to zero as well; they hold the value of a memory address where the instance of your class lives, and memory address zero is the Null Reference).
Please note that even if you are changing separate parts of the list in Update() , it can't be changed at the same time. I used a for loop to overcome this problem, but basically anything that can make a delay can be used for this.