Using the C# operator "??" can lead to unstable results

var bgMusicItem = GameObject.GetComponent<AudioSource>() ?? GameObject.AddComponent<AudioSource>();
Debug.Log(bgMusicItem.isPlaying);

Sometimes the code above may generate the following error:

MissingComponentException: There is no ‘AudioSource’ attached to the “SoundManager” game object, but a script is trying to access it.You probably need to add a AudioSource to the game object “SoundManager”. Or your script needs to check if the component is attached before using it.

Does anyone know why this happens?Any insight or information would be greatly appreciated.

This should be asked in the Scripting section.

You should tell more about how the script is used. From what I understand, “SoundManager” doesn’t originally have an audio component attached to itself and you use this code to add one?

If you do that, what about adding an audio component to “SoundManager” and script how and when it should play?

Stop using null coalescing operators in Unity.

Details are here:
https://nosuchstudio.medium.com/why-are-null-coalescing-operators-evil-in-unity-16f5a88d6071
and
https://blog.unity.com/technology/custom-operator-should-we-keep-it

1 Like

Thank you very much for your help!