NullReferenceException on AudioSource in prefab

Hi. I’m having some problems with playing sounds on prefabs. I’m throwing in an AudioClip to the script that I simply drag with the inspector to assign. Then I’m trying to play that clip with the AudioSource but I’m getting the NullReferenceException whenever I’m doing anything with that AudioSource. Needless to say Audio doesn’t play.

Here’s the code:

using UnityEngine;
using System.Collections;

public class Footsteps : MonoBehaviour {
	public AudioClip footsteps;
	private AudioSource footstepsSrc;
	
	void Start () {
		footstepsSrc = new AudioSource();
		footstepsSrc.clip = footsteps;
	}
	
	void Update () {
		if(GetComponent<Movement>().IsMoving())
		{
			if(!footstepsSrc.isPlaying)
				footstepsSrc.Play();
		}
		else
		{
			if(footstepsSrc.isPlaying)
				footstepsSrc.Stop();
		}
	}
}

1 Answer

1

This is a simple fix:

footstepsSrc = new AudioSource();

is not how you should add a component, but you should use this:

footstepsSrc = gameObject.AddComponent< AudioSource>();

Notice the lowercase g in gameObject which relates to the current GameObject we are running the script on. GameObject with a capital G is the class for all GameObject’s.

This is the proper way. Unity - Scripting API: GameObject.AddComponent

Works like a charm! Thanks!