Changing scene causes null reference exceptions

I have two perfectly working scenes I’d like to switch between, but whenever I do, I get a bunch of null reference exceptions. Can anyone explain why this happens?

A typical example is a script that plays an audio source. After reloading the current scene, or switching to a new one “audioSource” becomes null. Here is how I switch scenes:


And here is just one example of where a null reference exception occurs after changing scenes:

using UnityEngine;
using System.Collections;

public class Sounds : MonoBehaviour {

    public AudioSource spraySound;

    void Start()
        spraySound = GetComponent<AudioSource>();

    void OnEnable()
        spraycan.OnSprayStart += OnSprayStart;
        spraycan.OnSprayStop += OnSprayStop;

    void OnSprayStart()
        spraySound.Play(); // Null reference exception after reloading scene

    void OnSprayStop()
        spraySound.Stop(); // Null reference exception after reloading scene

I’ve been having a similar issue as well and have yet to resolve it.
If you have a chance, please post your actual error(s).

Also, there are several posts on StackOverflow regarding this very issue but none of the suggested solutions have actually worked for me.

Same problem here. Is there a solution?

First thing to do is checking if Start() is called and if GetComponent returns null there. Also check the call order. Is it possible that OnSprayStart is called before Start() is executed?

I don’t know if it’s relevant, but if you add callbacks in OnEnable you should remove them in OnDisable.

Found the problem. I missed disabling one callback. I’m using GameSparks. It was the message listener, catching all of the messages from the server:

void OnDisable() {
     GameSparks.Api.Messages.ScriptMessage.Listener -= GetMessages;