Hi!
I’m kind of new to Unity, but it seems in Unity 5 it was changed to where you had to have an audiosource component to play a sound effect, at least as far as I can figure.
Is there any way to avoid this? Having to attach every sound by both a script and an audio component is going to be a gigantic pain in the ass for me.
steego
June 29, 2015, 2:29pm
2
You can use AudioSource.PlayClipAtPoint which is a static function that doesn’t need an AudioSource.
That works, but you have no control over the audio after it starts playing. You can’t stop it, change the volume, etc.
OP, no Unity 5 didn’t change this. It was always that way. You need an Audio Source component to play sound.
If you don’t want to have to do that, you can invest in a plugin that does it for you (and much much more) such as the one in my signature.
I created a simple solution for those who want to access a audio source playing it (like me).
Add this class:
public static class SimpleSoundPlayer
{
private static AudioSource _source;
public static AudioSource PlaySound(AudioClip sound, float volume = 1f)
{
if (_source == null)
{
_source = new GameObject("SoundPlayer").AddComponent<AudioSource>();
_source.playOnAwake = false;
_source.loop = false;
UnityEngine.Object.DontDestroyOnLoad(_source.gameObject);
}
_source.clip = sound;
_source.volume = volume;
_source.Play();
return _source;
}
}
To use it simply do:
AudioSource targetSource = SimpleSoundPlayer.PlaySound(sound);