AudioSource loses reference (NullReferenceException)

I am trying to toggle music on and off inside script. On the Awake() method source has its reference set and it works but when I call the MusicToggle() method source gives NullReferenceException. I can’t see what is happening.

 private AudioSource source;

void Awake()	{
         .........
		source = GetComponent<AudioSource> ();
		source.mute = !SaveData.music;
        ..............
	}

 public void MusicToggle() {
        SaveData.saveData.ToggleMusic();
        source.mute = SaveData.music;
    }

And here is the error log;

NullReferenceException: Object
reference not set to an instance of an
object GameManager.MusicToggle () (at
Assets/Scripts/GameManager.cs:423)
UnityEngine.Events.InvokableCall.Invoke
(System.Object args) (at
C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:144)
UnityEngine.Events.InvokableCallList.Invoke
(System.Object parameters) (at
C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:621)
UnityEngine.Events.UnityEventBase.Invoke
(System.Object parameters) (at
C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:756)
UnityEngine.Events.UnityEvent1[T0].Invoke (.T0 arg0) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_1.cs:53) UnityEngine.EventSystems.EventTrigger.Execute (EventTriggerType id, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/EventTrigger.cs:67) UnityEngine.EventSystems.EventTrigger.OnPointerDown (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/EventTrigger.cs:93) UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerDownHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:38) UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerDownHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction1
functor) (at
C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update()

Basically, it’s saying, "Ok, so you’ve claimed this exists: GameManager.MusicToggle () within your script, but I don’t see that you’ve declared the variable at the top of your script. It’s like you’re saying “oh, yeah, just press the yellow button, but there’s no yellow button created yet.”.

Or, if you’re only showing part of your script in this post, and have declared the MusicToggle variable already… Make sure you go into the Unity interface, and assign a value/object/something to the script’s variable “musictoggle” if it is showing up within the interface area of the script.

Questions? Just write 'em, 'cause I’m not sure I’m being too clear at 1:02am here. … :smiley: