- Home /
Play sound once when variable is less than 0
So I have barricades that can be broken. When they are, I want them to play a sound ONCE. The problem is that the sounds is being looped instead of being played once. This is because the code states:
if (barricadeHealth <= 0){ playsound; }
How do I play the sound once every time a barricade goes below 0 hp?
Answer by NiloBR · Aug 11, 2015 at 11:28 AM
u can look at c# events.... you define a event like "onBarricadeDestroy", and subscribe to those events.... so you can execute some logic once they occur.... https://msdn.microsoft.com/pt-br/library/awbftdfh(v=vs.120).aspx
Answer by KdRWaylander · Aug 11, 2015 at 11:29 AM
Hi,
What you're looking for is the PlayOneShot() function :) Here you go: http://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html
And make sure that there is no loop property or so checked in the inspector of your audio file !
This is my code, the sounds gets looped because of update, but I need to have it in update to check hp. Sound is there aswell, therefore the loop. private SpriteRenderer sR; private HealthController hC; private AudioSource aS; private PolygonCollider2D polyC; private PlayerController playerC;
//variables
float maxHp;
float timeToSound = 0f;
float tempHp = 0f;
bool playSound = false;
// sound
public AudioClip hammering;
public AudioClip breaking;
// Use this for initialization
void Start () {
aS = gameObject.GetComponent<AudioSource> ();
polyC = gameObject.GetComponent<PolygonCollider2D> ();
sR = gameObject.GetComponent<SpriteRenderer> ();
hC = gameObject.GetComponent<HealthController> ();
maxHp = gameObject.GetComponent<HealthController> ().currentHealth;
tempHp = maxHp;
//Debug.Log (maxHp * 0.7);
}
// Update is called once per frame
void Update () {
// When wood is repairing
if (tempHp < hC.currentHealth && timeToSound <= 0) {
aS.pitch = Random.Range(1f, 1.21f);
aS.PlayOneShot(hammering);
tempHp = hC.currentHealth;
timeToSound = 4f;
}
if (timeToSound > 0) {
timeToSound -= Time.deltaTime;
}
if (hC.currentHealth <= 0) {
if (aS.isPlaying == false){
//aS.clip = breaking;
aS.loop = false;
aS.PlayOneShot(breaking);
}
polyC.enabled = false;
} else {
polyC.enabled = true;
}
}
then add a boolean "isToBePlayed" and do something like this:
bool isToBePlayed = false;
/* ...
Somewhere in your code your turn that boolean to true
when you want to "allow" the sound to be played
... */
void Update () {
if (!aS.isPlaying && isToBePlayed){
aS.PlayOneShot(breaking);
isToBePlayed = false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220611235340im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Collision with same gameobject only once 2 Answers
Audio issue - Trying Waitforseconds 0 Answers
Gunshot Sound Playing Too Many Times 1 Answer
Play sound ONCE! 3 Answers