NullReferenceException

Let’s say that I have a public static List in one script.

public static List<String> ClientNames;

Calling it from other script in specifically OnGUI() function gives me NullReferenceException.

ScriptName.ClientNames.Add("Rafael");   

It returns to me: NullReferenceException: Object reference not set to an instance of an object

I really have to do: ScriptName instanceName = GetComponent();?

As it turns out, any “reference” value can end up pointing at nothing, which your system calls “null”. If you try to access a reference which is currently null, your computer will warn you that you’re trying to access something which doesn’t exist. You need to make sure it exists before accessing it.

It’s important to distinguish two actions:

  • Declaring a variable gives it a name
  • Assigning a variable gives it a value

You’ve declared, but you haven’t assigned.

ClientNames = new List<String>();

You can do this all at once, too:

public static List<String> ClientNames = new List<String>();