I honestly don't understand what's going on. This was working perfectly fine yesterday. I have a GameObject in my scene that has an AudioSource attached. The AudioSource has a dragged in .wav file in it's AudioClip section. The GameObject also has a script attached. The script looks like:

using UnityEngine;
using System.IO;

public class MyData : MonoBehaviour {
    AudioSource audio;

    // Use this for initialization
    void Start () {
        audio = GetComponent<AudioSource>();

    void Update() {
        if (audio.isPlaying) { /* stuff */ }

The script compiles file, the audio plays fine, I've quadruple checked everything, but I keep getting the error "NullReferenceException: Object reference not set to an instance of an object" at the audio.isPlaying line.

  • \$\begingroup\$ Possible duplicate of NullReferenceException in Unity \$\endgroup\$
    – Hellium
    Commented Feb 26, 2018 at 11:01
  • 1
    \$\begingroup\$ Change your code in the Start function for this: void Start () { audio = GetComponent<AudioSource>(); Debug.Log("Audio source " + audio, gameObject) ; }. When the message is shown on the console, click on the message. The gameobject that yielded the message should be highlighted. Then, you will be able to see that there is no AudioSource component attached \$\endgroup\$
    – Hellium
    Commented Feb 26, 2018 at 11:03

1 Answer 1


Consider slapping a


attribute above this class definition, so that it's harder to accidentally end up with it on an object with no AudioSource to find with GetComponent.

When you add the script in the Inspector, it will automatically add an AudioSource if it's absent. And when you try to delete the AudioSource, it will warn you that another script is depending on it.

It won't do anything to help with existing objects in your scene/assets folders that were already misconfigured before adding this attribute though. For those, the debugging steps Hellium recommended are likely your best bet.

It also won't catch components deleted at runtime, but those generally fire a MissingReferenceException rather than a NullReferenceException, so I don't think that's the issue you're facing here.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .