Siddharth
Siddharth

Reputation: 4312

MissingReferenceException in AudioSource on DontDestroyOnLoad GameObject

I was getting Missing Reference Exception within my Audio Source when I change my game scene and again move back to the same scene.

Before I change the main menu scene, it is working fine but after changing and moving back to the main menu scene, it is started showing this exception.

enter image description here

Here is the code I have written for AudioManager:

public class AudioManager : MonoBehaviour
{
 static AudioManager instance;
 //
 [SerializeField] AudioClip buttonClickClip;
 [SerializeField] AudioSource myAudioSource;

 private void Awake()
 {
     instance = this;
 }

 public static AudioManager Instance
 {
     get
     {
         return instance;
     }
 }

 public void PlayButtonClickSound()
 {
     if (GameManager.Instance.IsEnableSounds)
         myAudioSource.PlayOneShot(buttonClickClip);
 }

}

Here is the code that I wrote for DontDestroyOnLoad purpose:

public class DontDetroyOnLoad : MonoBehaviour
{
 private static bool created = false;

 void Awake()
 {
     if (!created)
     {
         DontDestroyOnLoad(this.gameObject);
         created = true;
     }
     else
         Destroy(this.gameObject);
 }

}

Now please give me some suggestion to solve this problem.

Upvotes: 1

Views: 600

Answers (2)

zeroflaw
zeroflaw

Reputation: 564

Appreciate the answer from @jfish. That clearly describes the situation.

Here let me elaborate mine, on the example of using DontDestroyOnLoad

[SerializeField] AudioSource audioSource;
void Awake()
{
    GameObject[] objs = GameObject.FindGameObjectsWithTag("music");

    if (objs.Length > 1)
    {
        Destroy(this.gameObject);

        //Here, get the previous audioSource from previous game object
        audioSource = objs[0].GetComponent<AudioSource>(); 
    }

    DontDestroyOnLoad(this.gameObject);
}

On first load, it gets from Editor.

Subsequently, it gets from previous game object.

Upvotes: 0

jfish
jfish

Reputation: 91

You are referencing the AudioManager that you are destroying in the script that is trying to play the sound.

Think of it this way. You have

AudioManager A - DontDestroyOnLoad

AudioManager B - That gets destroyed cause A exists

In your scripts you are referencing AudioManager A when you first start up. Then when you leave the Scene and return you are now referencing AudioManager B, which got destroyed because A exists. All you need to do is always reference AudioManager A, not B.

Upvotes: 2

Related Questions