Search Unity

Audio getting a null reference exception on audiosource when changing scenes...

Discussion in 'Audio & Video' started by keblight, Oct 12, 2018.

  1. keblight

    keblight

    Joined:
    May 27, 2015
    Posts:
    34
    I have no problems in the initial scene that I set up my audio sources and clips, but when I switch scenes I always get a null reference exception as soon as the first call to reference a audiosource. I have looked through the forums and did a search for anything related and could not find anything. If anyone has any suggestions it would be much appreciated, thanks.
     
  2. keblight

    keblight

    Joined:
    May 27, 2015
    Posts:
    34
    got it fixed.
     
  3. mats1105

    mats1105

    Joined:
    Dec 21, 2018
    Posts:
    4
    I have the same issue, how did you fix it?
     
  4. c_Feng

    c_Feng

    Joined:
    May 15, 2017
    Posts:
    18
    There are many reasons why you may be unable to reference your audio source components and would need a little more info than is provided. However, here are some key points:

    1) When you "switch" scenes, is your initial scene / persistent game objects getting destroyed? Make sure you're using DontDestroyOnLoad appropriately or loading your scenes additively.
    2) Objects cannot be explicitly referenced across scenes unless you have some global (i.e. a static container) way to reference them.
    3) Depending on the way the audio sources are maintained across scenes, make sure your scripts are executing in order so that when you're trying to reference the audio sources, they are instantiated and available in the scene.

    I hope this helps.
     
  5. mats1105

    mats1105

    Joined:
    Dec 21, 2018
    Posts:
    4
    Thanks for reply! The container is global and the class is doNotDestroyOnLoad. As I am pretty new to this I don't fully understand what runs first and second so will take a look at that.

    I have provided a lot more information in this Unity questions post
     
    Last edited: Dec 31, 2018
  6. c_Feng

    c_Feng

    Joined:
    May 15, 2017
    Posts:
    18
    Your issue is the way you're attempting to get the reference to your AudioManager. I posted the solution in the questions post.