- Home /
Why am I able to play an AudioClip without an AudioSource?
I'm not sure why this is working. It seems that I am able to play AudioClips referenced in the script without having an AudioSource on the GameObject. In fact, I don't have an AudioSource anywhere in the scene.
I'm happy that it's working, but confused as to why. Any help?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GramGram : MonoBehaviour {
public List <AudioClip> audioClips = new List <AudioClip> ();
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1")) {
StartCoroutine ("Speak");
}
}
IEnumerator Speak () {
foreach (AudioClip clip in audioClips) {
AudioSource.PlayClipAtPoint (clip, transform.position);
yield return new WaitForSeconds (clip.length + 1f);
}
}
}
Answer by tanoshimi · Feb 20, 2015 at 09:13 PM
Read the documentation for the PlayClipAtPoint function:
"This function creates an audio source but automatically disposes of it once the clip has finished playing."
http://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
Ah, thanks.
I suppose then that PlayClipAtPoint is a resource-efficient way to play sound effects, relative to other options like Play and PlayOneShot?
I'm not sure if this is still the case, but PlayClipAtPoint used to create and destroy an object to play the sound. This would make it more expensive than the alternatives.
From our own tests PlayOneShot is marginally better than Play, but you can't test for things like isPlaying.
Depends how you define "resource efficient".... As the documentation and Ooweeoo state - PlayClipAtPoint (and PlayOneShot) creates and then destroys an AudioSource component just to play the clip. That's "efficient" if you mean that you don't have to have an audiosource persisting in the scene when it isn't required. But it's certainly not "efficient" because it allocates and then destroys an object, requiring the garbage collector to clean up memory.
Generally speaking, they're to be avoided, especially on mobile devices.
Thanks for the feedback. I'll keep those things in $$anonymous$$d and do some reading up my own as well.
Old thread, I use pathelogical games pool manager, and I was curiouse, I just reworked my audio system to used a pooled prefab with an audio source (I set the clip and play then despawn it) pathelogical enables / disables but DOES NOT create / destroy. Any idea if this is more or less efficient then just PlayClipAtPoint?
Your answer
Follow this Question
Related Questions
Making AudioSource follow camera? 1 Answer
A better script for a machine gun? 1 Answer
GetSpectrumData - what does it fill the samples argument with exactly? 0 Answers
AudioClip stuttering while loop is OFF and not using function Update? 1 Answer
Browsers prevent WebGL Audio to start at Awake. How to get notification of actual Audio start? 0 Answers