- Home /
Play audio.PlayOneShot() once in an Update() function
Hi there,
I have looked through many forums and have tried all sorts of methods (booleans, invokes, coroutines) and cannot get a sound to play only once when my character performs an animation (swiping), because it's in an UpdateDestination() function. Here is my code:
using UnityEngine;
using System.Collections;
public class BowserController : MonoBehaviour {
public Transform target;
public NavMeshAgent agent;
public bool stopUpdates = false;
public AudioClip runSound;
public AudioClip attackSound;
void Start() {
InvokeRepeating ("runningSound", 0.0f, 0.5f);
}
void Awake () {
agent = GetComponent<NavMeshAgent>();
InvokeRepeating("UpdateDestination", 0.1F, 0.1F);
}
void UpdateDestination(){
agent.SetDestination (target.position);
if (agent.remainingDistance > agent.stoppingDistance) {
animation.CrossFade ("chasing (1)", 0.3F);
stopUpdates = true;
}
else{
animation.CrossFade("swipe",0.3F);
audio.PlayOneShot (attackSound);
}
}
void runningSound ()
{
if (agent.remainingDistance>agent.stoppingDistance) {
audio.PlayOneShot (runSound);
}
}
}
My character's sound plays rapidly at multiple times. I'm sure you've come across this problem before and probably have an easy fix, but I just can't get my head around it! I thought it would be a simple solution but after many attempts I still cannot resolve this issue. Your time and support would be thoroughly appreciated.
Many thanks.
Answer by xortrox · May 05, 2014 at 05:53 PM
if(!audio.isPlaying)
{
audio.PlayOneShot(attackSound);//use the same check for runSound
}
Answer by Li0nSword · May 04, 2014 at 02:50 AM
Try using this:
AudioSource.PlayClipAtPoint(runSound, transform.position);
I use it and it plays only once. If that doesn't work and you want to continue using your method then I suggest using a boolean to check if the sound has just played.
@Li0nSword That didn't work. Remember it's the attacking sound that I want to play. I'll experiment with booleans though. Thanks anyway!
@A$$anonymous$$J9 Just change the variable from runSound to attackSound. What do you mean by it didn't work? Does it not play at all or does it still play multiple times?
Your answer
Follow this Question
Related Questions
Update character's position after animation 1 Answer
Calling sound once in update 1 Answer
Trigger diferent sounds playing from the same object 1 Answer
Multiple Cars not working 1 Answer
Play animation once in a update 1 Answer