How to CHECK IF AN OBJECT EXISTS in Unity to avoid NullReferenceException error

Опубликовано: 15 Октябрь 2024
на канале: GDT Solutions ES
3,162
71

In this video we see two ways to check if a variable has an assigned object in order to use it only if it is initialized, this way we can avoid a NullReferenceException error at runtime.
A NullReferenceException error in Unity will not crash the game or application but it can be problematic since instructions below the point where the error occurs will not be executed.

The first method consists of checking if the variable that is supposed to have assigned the GameObject or component that we want to use has a value different from "null", that is to say if it has been initialized, in affirmative case we can use that variable without problems.

The second one can be used when getting a component from a GameObject, maybe the component we are looking for is not assigned to the GameObject, in this case we can apply the first method and after doing a GetComponent, check if the GetComponent has returned null, but we can also use a function called "TryGetComponent" that "tries" to get the component and returns true or false depending on whether it succeeds in getting it or not and also stores the component in the variable that we indicate as "out". This function can be used in conjunction with an if statement and execute a task only if the GameObject has a particular component assigned to it.

An example of the use of these methods could be during a collision of two objects, if it is detected that one of them has an AudioSource component, force the playback of the AudioSource component, but if the colliding GameObject does not have an AudioSource component, do nothing.

INTRODUCTION VIDEO OF THE REFERENCE SERIES IN UNITY:
   • Video  

____________________________________________________________
LINKS

Portfolio: https://gamedevtraum.com/en/portfolio...

LinkedIn:   / gamedevtraum  

Downloads: https://gamedevtraum.itch.io/

Contact 1: [email protected]

Contact 2:   / gamedevtraum  
____________________________________________________________