Intentional null references are forcefully changed on selecting the object in the editor

I have a bit of a strange bug here. I’m using intentional null references as a means of checking whether or not a Worker class has an assigned job. When the worker is idle and looking for a job, the variable that stores the job inside the Worker class will be an intentional null reference, which I can then check for. Now, when I’m testing my code in the editor, I have to select the object with the Worker script attached to it to see what it’s current job is. For some reason, when I do this, the intentional null reference is forcefully set to a default value that is not null, causing an error when the Worker tries to do a job that does not exist. I have no idea why this is happening. I would assume it has something to do with the editor wanting to display a value that is not null, and changing the reference in the process, but I’m not sure. Any help would be appreciated.

Unity tries to be helpful and assign a “default” value for any serializable field on a MonoBehaviour. If your intention for having a public variable is so you can observe the worker’s current job, rather than actually changing it, you can work around Unity’s “helpfulness” with some clever usage of properties:

// This string will show in the inspector
public string currentJobDescription = "null";
Job currentJob;
public Job Job {
  get => currentJob;
  set {
    currentJob = value;
    if (value == null) {
      currentJobDescription = "null";
    }
    else {
      currentJobDescription = value.ToString();
    }
  }
}

You will probably want to write a useful ToString() method for your Job class for this to be the most informative.

So it’s not a bug, but rather Unity trying to be helpful. I see. Anyways, thanks for the help.