Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

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

Discussion in 'Audio & Video' started by hangsg, Nov 8, 2023.

  1. hangsg

    hangsg

    Joined:
    Nov 8, 2023
    Posts:
    2
    Code (CSharp):
    1. var bgMusicItem = GameObject.GetComponent<AudioSource>() ?? GameObject.AddComponent<AudioSource>();
    2. 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.
     
  2. APSchmidt

    APSchmidt

    Joined:
    Oct 31, 2023
    Posts:
    262
    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?
     
    Last edited: Nov 8, 2023
  3. Last edited by a moderator: Nov 8, 2023
    hangsg likes this.
  4. hangsg

    hangsg

    Joined:
    Nov 8, 2023
    Posts:
    2