Please help with my audio null reference exception

I haven’t encountered a dev-blocking issue like this in a long time, but something is happening that I can’t explain and it has broken my game.

Quick overview: I am playing sound effects using a public static audio manager, and I have an array of sound effects SFX[ ]. It seems that the actual playing off the SFX isn’t happening at all now, and I haven’t changed enough in the code (I think) to have encountered this issue. Any help is appreciated!

So, for example, this is a script for a sign post which simply updates the UI and plays a sound:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SignPost : MonoBehaviour
{
    public string textToDisplay;
    public int signPostSound;

    public bool isHub;

    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
      
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            if (!isHub)
            {
                Debug.Log("Sign triggered");
                AudioManager.instance.PlaySFX(signPostSound);
                Debug.Log("Sound triggered");
                UIController.instance.messageText.text = textToDisplay;
                UIController.instance.DisplayMessage();
            }
            else
            {
                AudioManager.instance.PlaySFX(signPostSound);
                HubUIController.instance.messageText.text = textToDisplay;
                HubUIController.instance.DisplayMessage();
            }

        }

    }
}

And here is the public static audio manager:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance;

    private float randomSong;
    public bool isHub;

    public AudioSource levelMusic, gameOverMusic, winMusic, bossMusic, starPowerMusic, hubMusic;
    public AudioSource[] hubMusicSoundtrack;

    public AudioSource[] SFX;
  
    //private AudioSource[] allAudioSources;


    /*void Awake()
    {
        allAudioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[];
    }*/

    // Start is called before the first frame update
    void Start()
    {
        if (isHub)
        {
            PlayRandomSong();
            //Invoke("PlayRandomSong", hubMusic.clip.length);
        }
    }

    // Update is called once per frame
    void Update()
    {
      
    }

    void PlayRandomSong()
    {
        hubMusic = hubMusicSoundtrack[Random.Range(0, hubMusicSoundtrack.Length)];
        hubMusic.Play();
        Invoke("PlayRandomSong", hubMusic.clip.length);
        Debug.Log("play song " + hubMusic);
    }

    public void PlayGameOver()
    {
        levelMusic.Stop();

        gameOverMusic.Play();
    }

    public void PlayBossMusic()
    {
        levelMusic.Stop();

        bossMusic.Play();
    }

    public void PlayLevelWin()
    {
        levelMusic.Stop();

        winMusic.Play();
       
    }

    public void PlaySFX(int sfxToPlay)
    {
        Debug.Log("PlaySFX started");
        SFX[sfxToPlay].Stop();
        Debug.Log("SFX stopped");
        SFX[sfxToPlay].Play();
        Debug.Log("SFX played");
    }

    public void StopSFX(int sfxToPlay)
    {
        SFX[sfxToPlay].Stop();
    }

    public IEnumerator FadeAudioSource(AudioSource audiosource, float duration, float targetVolume)
    {
        float currentTime = 0;
        float start = gameOverMusic.volume;

       // targetVolume = 0;
       // duration = 2;

        while (currentTime < duration)
        {
            currentTime += Time.deltaTime;
            audiosource.volume = Mathf.Lerp(start, targetVolume, currentTime / duration);
            Debug.Log("Audio volume is " + audiosource.volume);
            yield return null;
        }
        yield break;
    }

    /*public void StopAllAudio()
    {
        foreach (AudioSource audioS in allAudioSources)
        {
            audioS.Stop();
        }
    }*/

}

Apologies for all the omitted lines.

The console error happens at this line from the sign post script:
AudioManager.instance.PlaySFX(signPostSound);

But please note all the debug lines in both scripts. Right now, I am only seeing the very first debug:
Debug.Log(“Sign triggered”);

But nothing else. I do not understand what I have done. Please help, thank you!

There’s nowhere in the code where AudioManager.instance is assigned, and you try to access it in between your two debug statements. That’s your null.

I assume AudioManager is supposed to be a singleton, in which case there would typically be a line like this in AudioManager’s Awake():

instance = this;
2 Likes

Goddammit I love you. Who are you. You’re the best. Thank jebus for you.

Expect to see the Null Reference error a LOT. It’s easily the most common error to commit when working. Learn how to fix it rapidly. It’s easy.

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.