- Home /
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();
}
}
}
Answer by EliteMossy · Apr 02, 2013 at 01:04 PM
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. http://docs.unity3d.com/Documentation/ScriptReference/GameObject.AddComponent.html
Your answer
Follow this Question
Related Questions
Play audio using prefab warnings 2 Answers
Do unused audio sources hurt performance? 0 Answers
Audio, play when laser hits object 1 Answer
detect audio then record and then play 0 Answers