Unity Version: 2021.3.5f1
System: Windows 10 Pro 22H2 19045.2364
I got null reference error after accessing serialized field that was set as default reference in script.
public class DialogueEditor : EditorWindow
{
private static Dialogue _selectedDialogue;
[SerializeField] private DialogueActor playerDialogueActor;
[SerializeField] private GUIStyleSO styleNodeBasic;
private void OnEnable()
{ if (playerDialogueActor is null)
{
Debug.LogWarning("Player Dialogue Actor is null");
}
if (styleNodeBasic is null)
{
Debug.LogWarning("styleNodeBasic is null");
return;
}}
}
The SerializeField was filled with ScriptableObject (no missing script or compile error).
I will always get the Debug.LogWarning printed (indicating that they are null).
You’re correct, and I admit my fault of not looking at the code closely enough.
Before I give wrong information, I’m confused as to why you’re using “is” to compare something to null, that usually checks types, and it should return false every time, so it doesn’t make sense why it’s true.
Edit: My assumption is incorrect, apparently in C# 7 you can do this, and is just new to me. Ignore what I said.
Thanks for asking, but that is not related to the topic, I already tried to switch “is null” to “!= null” or (!variable) but the results are the same.
The reason why I am using “is null” rather than “!=” is when if you override the “!=” operator for a class and make it always return true, “!=” will not always return correct result, on the other hand, the “is null” will always return the correct result.
So, I don’t know specifically why you can’t do this, but it didn’t really seem like intuitive behavior that this would work like this. Just a guess, but it’s probably intended that it doesn’t work.
I believe you can do a workaround if it’s absolutely necessary, but it seems like more work than it’s worth. There’s the method GetDefaultReference, which you can put in the name of the value to get the default one set in the MonoScript.
Honestly I would just set the values when you create the component.
Thanks for the help, but this script is inheriting EditorWindow class not Monobehavior, so I did not add it to any GameObject. And currently I have not found other way to set the reference other than default reference.
I found a walk around, that is to use Resource.Load to set the default reference, but still this is not the normal way to do it, and I lost default reference feature for this script.