NullReferenceException when calling another script

Hi all,

I have a gameobject with 2 scripts and an Audio Source component.

My first script is called BoardManager and it contains to following code:

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

public class BoardManager : MonoBehaviour {

    AudioManager audioManager = new AudioManager();

    void start() {
        audioManager.PlaySound("sound1");
    }

}

The second script is called AudioManager and it contains the following code:

using UnityEngine;
using System.Collections;

public class AudioManager : MonoBehaviour {

    public AudioClip sound1;

    public void PlaySound(string soundName) {

        AudioSource audio = GetComponent<AudioSource>();

        if (soundName == "sound1")
            audio.PlayOneShot(sound1);

    }

}

When the BoardManager script calls the PlaySound function from the AudioManager script it gives a NullReferenceException error on the line:

AudioSource audio = GetComponent<AudioSource>();

If the PlaySound function is in the BoardManager script, it works fine.

Why can’t the AudioManager script find the AudioSource component if it is called from the BoardManager script if they are in the same gameobject and the Audio Source is next to both of them?

Is there a way to fix this?

Thanks.

Don’t new on a class that inherits MonoBehaviour, it will mess up a lot of stuff.
One of the things it “breaks” is that an object created like this is not attached to any GameObject, which is why you’re getting a NRE.

This line needs changing:

AudioManager audioManager = new AudioManager();

If you change it like this:

public class BoardManager : MonoBehaviour {
    AudioManager audioManager;
    void Start() {
        audioManager = GetComponent<AudioManager>();
       if (audioManager == null)
              throw new UnityException("Couldn't find AudioManager!");
        audioManager.PlaySound("sound1");
    }
}

it should work.

Sidenote - unless you’re using other techniques, checking if your GetComponent actually returned what you expected is a good idea (see the null check above).
Same could/should be done in the AudioManager script (add a Start, get reference to the AudioSource there, check if it’s successful). It also saves GetComponent calls.

PS. C# is case-sensitive, be careful about that. In your original script you have void start() where you should have void Start()

1 Like

Thanks a lot, it works!