I’m developing a game where I can destroy objects, including those that may be playing animations. I used the null-conditional operator (?.) to avoid errors, but I’m still encountering issues. In my code, I have a PlayAnimation method that uses the ?. operator to call the Play method on the anim object. However, I’m getting errors even with this approach. I’m using the 2022 version of Visual Studio
using UnityEngine;
public class Door : MonoBehaviour
{
public GameObject door;
public Animator anim;
public bool open = false;
private void Update()
{
PlayAnimation(open ? "DoorOpen" : "DoorClose");
}
private void OnTriggerStay(Collider other)
{
open = other.CompareTag("Player");
}
private void OnTriggerExit(Collider other)
{
open = false;
}
private void PlayAnimation(string state)
{
anim?.Play(state);
}
}
2
Answers
Take a look at OnTriggerStay method. maybe "other" is null !
The
?.
operator checks for truly null references, whereas Unity overrides the==
operator for Unity objects to make references to destroyed objects be equal to null. So you cannot use this operator in these situations. Just replace it with: