-
-
Notifications
You must be signed in to change notification settings - Fork 21
Closed
Labels
enhancementNew feature or requestNew feature or request
Description
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}");
}
}- Add CodeExample on a GameObject (1) and another GameObject (2)
- Reference CodeExample from GameObject (2) in CodeExample on GameObject (1)
- 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 requestNew feature or request