Skip to content

Add support for null checks #33

@marc-antoine-girard

Description

@marc-antoine-girard

Considering this Code:

public interface IDog { }
[ExecuteAlways]
public class CodeExample : MonoBehaviour, IDog
{
    public SerializableInterface<IDog> MyVariable;

    private void Update()
    {
        Debug.Log( $"{MyVariable.Value == null} {ReferenceEquals(MyVariable.Value, null)} {(Object)MyVariable.Value == null}");
    }
}
  1. Add CodeExample on a GameObject (1) and another GameObject (2)
  2. Reference CodeExample from GameObject (2) in CodeExample on GameObject (1)
  3. Then delete GameObject (2)

Output in Console: "False, False, True".

The third value is the expected behaviour, since the referenced Component has been destroyed. This happens because, by default, we're not using Unity's equality operator.

A clean way to handle this would be to add this method in SerializableInterface:

public bool IsValueNull() => Value == null || Value.Equals(null);

or

// which is a code that can actually be found in the Visual Scripting package - ish
// Unity.VisualScripting.UnityObjectUtility.IsUnityNull
public bool IsValueNull() => Value == null || (Value is UnityEngine.Object obj && obj == null);

Now with the following code, doing the same steps:

public interface IDog { }

[ExecuteAlways]
public class CodeExample : MonoBehaviour, IDog
{
    public SerializableInterface<IDog> MyVariable;

    private void Update()
    {
        Debug.Log( $"{MyVariable.IsValueNull()} {ReferenceEquals(MyVariable.Value, null)} {(Object)MyVariable.Value == null}");
    }
}

Outputs: "True, False, True"

Relevant articles

https://sometimesicode.wordpress.com/2020/04/01/null-check-and-equality-in-unity/
microsoft/MixedRealityToolkit-Unity#5981 (comment)

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions