Adding sound to my battery script

Hey guys,

I'm having a slight problem adding sound to my battery which is gradually running low on power. Every time the battery goes down by a bar, I want to add a sound all different in pitch which I have made already.

This is my current script.

static var charge : float;

var charge1tex : Texture2D; var charge2tex : Texture2D; var charge3tex : Texture2D; var charge4tex : Texture2D; var charge0tex : Texture2D;

function Start (){ guiTexture.enabled = true; charge = 40; }

function Update () {

   if (charge > 30) {
           guiTexture.texture = charge4tex;
   }
   else if (charge > 20) {
           guiTexture.texture = charge3tex;
   }
   else if (charge > 10) {
           guiTexture.texture = charge2tex;
   }
   else if (charge > 5) {
           guiTexture.texture = charge1tex;
   }
   else if (charge > 0) {
           // todo: make this flash...
           guiTexture.texture = charge1tex;
   }
   else {
           guiTexture.texture = charge0tex;
   }

}

If you could pass on any suggestions, I would be very grateful. Thank you

http://unity3d.com/support/documentation/ScriptReference/AudioSource.PlayOneShot.html

So, you dont know how to add sound to a object?

First you need to add a audioSource to your object. Click the object you want to add the audioSource to and go to component->Audio-> AudioSource.

The you need to do some scripting:

var sound : AudioClip; // Fill this in the inspector

//When needed call:
audio.PlayOneShot(sound);

Thanks for your responses.

So I have to use 4 variables for the four different sounds I want for my battery? It gradually goes down in power on the HUD.

It would appear so. Also, just as a little hint... Your code will never get past the first conditional the way you've got it written there. Imagine the charge is 19. You want guiTexture.texture = charge3tex; to execute in that case, because 19 < 20. 19 is also less than 30, so the first conditional is the only one that ever gets executed when charge drops below 30.

You could add "&& charge > 20" to the top one, then "&& charge > 10" to the second, and so on, to make sure the execution filters into the right conditional. :)