- Home /
Getting an AudioSource to play?
I used to have a script that would get my player prefab to play a 2D sound whenever a specific object was instantiated. I recently updated to Unity4.1 (previous version was 3.5.x) and now my script doesn't work, and I constantly get an error saying
UnityEngine.AudioSource:PlayOneShot(AudioClip) I did do some research and it's apparently because it won't play a sound from a prefab but I can't seem to find another way of doing this. This is my script on the Instantiated object. var explosionSound : AudioClip; var audioSource : AudioSource;Can not play a disabled audio source
function Start(){ audio.enabled = true; audioSource.PlayOneShot(explosionSound); }
Where audioSource is my player prefab, and I have 2 slightly modified versions of that prefab in my scene (player 1 and player 2) What is the best possible way to get my sound played? Any help would be greatly appreciated.
$$anonymous$$y first quess is either the gameobject this script is attached to does not have an AudioSource or it is not enabled through the checkbox in the Inspector
Answer by psycocrusher · Mar 29, 2013 at 09:39 PM
You dont need a script for that, drag your audio file on the audio source, and check "Play on Awake" and uncheck "Loop".
The audio should only play once when you instantiate it.
That would make sense, however the gameobject destroys itself after a second, and the audio clip lasts 2-3 seconds. so I end up hearing only part of the file.
That is why my previous answer (that I removed since it was not what you wanted but I can put it back) was using AudioSource.PlayClipAtPoint which actually creates a new object of type AudioSource that will live for the duration of the audio clip. It will actually show in the hierarchy as an independant object meaning that destroying the object that created it will not affect its life. But you said this would not fix your issue.
I don't remember seeing an answer about PlayClipAtPoint, the only other answer I saw was someone suggesting audio.Play()
How do you implement PlayClipAtPoint?
Oops I meant PlayOneShot. But you can try PlayClipAtPoint:
AudioSource.PlayClipAtPoint(sound, transform.position);