Search Unity

CustomEditor for StateMachineBehaviour causing NullReferenceException on game start

Discussion in 'Editor & General Support' started by arvzg, Apr 28, 2020.

  1. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    619
    I'm fairly certain this is a Unity bug, but need to confirm - and see if there's any way to work around it.

    On Unity 2018.2.11 (and we cannot upgrade for now)

    CustomEditor for StateMachineBehaviours are causing NullReferenceException(s) after the StateMachineBehaviour is removed. Restarting Unity 'fixes' this temporarily, until you create another SMB and remove it again. Each time an SMB with a CustomEditor is removed, it adds 1 NullReferenceException to the console when the game starts - until you restart Unity.

    Here's the basic steps to reproduce:

    • Create a new StateMachineBehaviour script, and add at least 1 Serialized field
    • Create a custom editor for the StateMachineBehaviour, add a SerializedProperty, and use FindProperty in OnEnable()
    • Add the SMB on any Animator State. Then remove it.
    • Play game, and Exception is immediately thrown:
    upload_2020-4-28_13-40-2.png

    It's Nulling out on serializedObject, which I use to call serializedObject.FindProperty(..), because the serializedObject doesn't exist anymore because it's been removed.

    It's very strange that the Editor's OnEnable is getting called at all - I make sure to deselect the Animator State before playing the game, so I am not inspecting the SMB. A custom Editor shouldn't be running OnEnable unless I am inspecting the component it's made for.

    This is almost definitely a Unity bug, right? What can I do to stop these exceptions from happening? (p.s. checking if serializedObject == null doesn't work, still causes the exception)
     
  2. arvzg

    arvzg

    Joined:
    Jun 28, 2009
    Posts:
    619
    Ok I think what's actually happening (or not happening) is that when you right click > Remove a StateMachineBehaviour, it does not Destroy the CustomEditor that is running alongside it. So you end up with a CustomEditor hanging around in memory that has no reference to its target object. I figured this out by adding debug logs in OnDestroy(), which are called appropriately when you deselect the SMB, but does not get called when Removing the SMB

    So now I'm 100% convinced it's a unity bug, now to figure out how I can maybe fix this...