AudioSource causes null reference exception

Hi,

I’m simply trying to make an audio clip play on loop. I have the following code:

public AudioClip gallop;
AudioSource gallopSrc;

gallopSrc = new AudioSource();
gallopSrc.clip = gallop;
gallopSrc.loop = true;
gallopSrc.Play();

Also tried:

gallopSrc.PlayOneShot(gallop);

I always get the error NullReferenceException on the first line that mentions gallopSrc after the line gallopSrc = new AudioSource();. So it seems that gallopSrc is not being initialised.

I have assigned the correct audio clip to ‘gallop’ in the inspector. I have some other sound effects working by using the following code:

AudioSource.PlayClipAtPoint(gallop, Camera.main.transform.position);

However, this way doesn’t allow me to loop.

An AudioSource is a component, not something you create with new. You would normally have it already added to a gameobject, or else use AddComponent.

–Eric

2 Likes

Ok, I’ve scrapped that code and added an Audio Source component to my player object. I dragged the audio clip in and ticked loop. ‘Play on awake’ is ticked and it says it will play the sound when the scene loads. But nothing plays when I run it. Do I need to do a GetComponent in code and play it?

Got this working by going to the Audio Importer settings on the audio clip and unticking ‘3D Sound’. I will do this with all my audio clips now as its a 2D game.