- Home /
Play sound ONCE!
I need to trigger sound at the beginning of an action, and for it to play ONCE, and one time only. The thing is, I have all of my actions in an Udate function! I can't seem to force a sound clip to play through only one time- update keeps calling every frame. I cant link it to a coroutine either, because my intial commands are in Udate. I saw a post explaining something along the lines of using
animation["action"].time
but I can't seem to get it going. I've tried
}if (animation["attack"].time ==.1){
audio.PlayOneShot(blast);
but that doesn't trigger it all.
I just need sound to play once on an action! Does any know of a work around? My models are from 3ds max, and and animation events seem over the top for something so simple. Thanks in advance!
Just a little hint: something like if (animation["attack"].time ==.1)
is like playing lotto. A float can have very small variances. 0.1 is not the same as 0.10001 or 0.099999 . $$anonymous$$aybe use an AnimationEvent ? http://unity3d.com/support/documentation/Components/animeditor-AnimationEvents.html
Ohh, just read you don't want to use AnimationEvents, well if your condition is an exact animation time i strongly recommend them. You can of course check if the time is greater than .1 and in addition do the check that efge mentioned.
It does make since to use an exact animation time, but (animation["attack"].time ==.1) doesn't trigger the sound. If I say to use any time greater than 1, then sound will play every second still. Any Ideas?
Thanks, but we are overlooking it... It really needs '0' for what to check for with time! See me answer, and thank you for helping.
Answer by superventure · May 20, 2011 at 10:59 PM
Found a solution. I was close in my original attempt:
if(animation["x"].enabled && animation["x"].time == 0)
audio.clip = xsound;
audio.Play();
When you think about it, all sound clips are equal to zero at one point, so this will be a sure thing to check ONCE and one time during the life of the animation.
Answer by efge · Mar 01, 2011 at 11:04 PM
To play a sound once at the beginning you could play it in the function Start() or set your AudioSource in the inspector to PlayOnAwake true, Loop false.
To play a sound once during Update() use a boolean variable or instantiate a GameObject with an AudioSource with the same settings.
function Start() { soundplayed = false; }
function Update () { if (!soundplayed) { audio.PlayOneShot(blast); soundplayed = true; } ... }
You are super awesome! This code helped me to figure out how to play a jump landing sound once the player presses the jump button. Thank you so much!!!!!!
Answer by cody01100011 · Jun 30, 2021 at 10:13 PM
sourse code ( https://docs.unity3d.com/ScriptReference/AudioSource.Play.html )
public AudioSource My_audio;
void Start(){
My_audio.Play();
}
void Update{
if (distanse > 10) { My_audio.Pause (); }
if (distanse < 10) { My_audio.UnPause (); }
}