I have assigned it, but I get an error of Unassigned Reference Exception!
I have a GameObject with a script and an Audio Source. The Audio Source is assigned to the variable of the script. While testing the game in Play mode though, the sound doesn't work, and I get an Unassigned Reference Exception Error!
I tried assigning the audioPlayer variable both by dragging and dropping the Audio Source component in the Inspector, and using the GetComponent() method. None worked.
Now why is this happening ?
Edit: Here is some more info:
I used to initiate the Audio Source variable with a call to GetComponent() in the Start() function of the script, and the call to the source's Play() function would take play whenever the character would press the attack button.
And although in the beginning it was working, something happened and then it wouldn't. But I tried this: Using the GetComponent() in the function that is called when the player hits the attack button. This way the sound plays! Although its play is delayed because it has to get the component the moment it needs to play the sound.
I tried
Can you share the stack trace for this error message?
Answer by AMU4u · Feb 23, 2017 at 02:54 AM
[RequireComponent(typeof(AudioSource))]
void SomeClass : MonoBehaviour
{
AudioClip attackSound;
void Start()
{
attackSound = GetComponent<AudioSource>().clip;
}
I retrieve the actual clip in this situation so you can load it from Resources or prefabs or change it dynamically right from the go! Be sure to remove the script from the GameObject and put it back on or this WON'T work for some dumb reason.
I've done that, and it doesn't disappear. If I tick "Play on Awake", the sound does play on awake. But otherwise I get this error. :/
You solved your own issue already, you just don't know it yet!
In your start function, that is when you want to do GetComponent<>.
Reading your issue again, I would take it OUT of the variable and make it just a component of the GameObject. An easy way to do this is [RequiredComponent(typeof(whatever))] and be sure to drag and drop the script onto the game object again to get it to automatically add the audio source to the script.
[RequiredComponent(typeof(audiosource))]
void SomeClass : mono {
Audiosource attackSound;
void Start(){
attacksound = getcomponent<audiosource>();
attacksound.wav = whatever
}
^ this is psuedo code but basically should work flawlessly.