Search Unity

Audio NullReferenceException when trying to get AudioSource

Discussion in 'Audio & Video' started by furiousgreen, Dec 20, 2018.

  1. furiousgreen

    furiousgreen

    Joined:
    Jul 30, 2018
    Posts:
    1
    Hi,

    I have an AudioSource added to my project and it plays sound properly.
    When I try to access the AudioSource to pause/unpause I get a NullReferenceException.

    Here is the code I've been using below:


    Code (CSharp):
    1. private AudioSource audioSource;
    2.     void OnApplicationPause (bool isPaused)
    3.     {
    4.         Debug.Log ("unity-script: OnApplicationPause = " + isPaused);
    5.         audioSource = GetComponent<AudioSource>();
    6.         if (isPaused == false)
    7.         {
    8.             audioSource.Pause();
    9.         }
    10.         else
    11.         {
    12.             audioSource.UnPause();
    13.         }
    14.     }
     

    Attached Files:

  2. knobblez

    knobblez

    Joined:
    Nov 26, 2017
    Posts:
    223
    " audioSource = GetComponent<AudioSource>(); "

    Is this script attached to the same GameObject that's holding the audio source? If not you need to reference it, which would explain the nullreference