Play Audio when condition is met

Hey guys! I’m just getting used to Unity 5 and have run into a problem when making my game.

As you can see in my code below, when the value, click.ore is more or equal to the cost, it will change the color of the icon, and well as play a sound effect. Whilst the color works, the sound is very distorted and keeps playing for a very long time, not working again when i reach my next value. To give you a clearer picture, here is a screenshot!

void Update(){
        itemInfo.text = itemName + " (" + count + ")" + "\nCost: " + cost + "\nPower: +" +clickPower;

        if(click.ore >= cost) {
            GetComponent<Image>().color = affordable;
            GetComponent<AudioSource>().PlayOneShot(ding);




        } else {
            GetComponent<Image>().color = standard;
        }




      
    }

could anyone help me so that the sound plays correctly when the value is met instead of getting this distorted effect. Thank you!

because update is called a lot you code will execute a lot
call play once from a button handler instead of continually from update

And how would i go about doing that if you don’t mind me asking :)?

No matter! i fixed it by using a bool in my updateFuction to check if the ding sound had played or not! :slight_smile:

You would put a function like this on the game object, and in your button’s event triggers you would add a reference to this function and pass in the amount of ore if you wanted to. For more on buttons see the information linked below. =P

private int ore = 0;
public int enoughOre = 10;

public Color affordable;
public Color notAffordable;

private Image image;
private AudioSource source;

public void AddOre(int amount = 1)
{
   ore += amount;

   if(!image){
      if(GetComponent<Image>())
         image = GetComponent<Image>();
      else return;
   }
   if(!source){
      if(GetComponent<AudioSource>())
         source= GetComponent<AudioSource>();
      else return;
   }

   if(ore >= enoughOre){
      GetComponent<Image>().color = affordable;
      GetComponent<AudioSource>().PlayOneShot(ding);
   }
   else{
      GetComponent<Image>().color = notAffordable;
   }
}

http://docs.unity3d.com/Manual/script-Button.html
http://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button