Unity3D – Play a sound in sync with a countdown

Create a scene with:

– Main Camera

– Cube, attach the script:


#pragma strict

// AudioCountDown() variables START ################################################################
var pinPulled : boolean = false;
var fuse : float = 8.5; // the grenade explodes x seconds after the pin is pulled
var fuseTimer : float = 0;
var grenadeBeep : AudioClip;
var slowInterval : float = 1.0; // slow speed SFX
var fastInterval : float = 0.2; // fast speed SFX for last seconds
private var nextTime : float = -1; // declare this variable outside any function so every function can acces 
// AudioCountDown() variables END ##################################################################

function Start () {
} // END Start

function Update () {
		AudioCountDown();// call the audio for the CountDown	
}// END Update

function OnMouseDown ()
{
        // When you click over the object
        pinPulled = true; // the grenade pin will be pulled
        Debug.Log('Pin Pulled!');
}// END OnMouseDown()

function AudioCountDown(){
	// Audio CountDown START ##################################################################
	//If a grenade's pin has been pulled, start the countdown
	if (pinPulled) {
	   fuseTimer -= Time.deltaTime;
	}
	else { // pin in place: reset fuseTimer and nextTime
	   fuseTimer = fuse;
	   nextTime = fuseTimer - slowInterval; // set time for 1st tick
	}
	 
	if (fuseTimer <= nextTime) { // it's time to tick:
	   if (fuseTimer < 3.0){ // if entered fast range (last second), use fast interval
	       nextTime -= fastInterval;
	   } else { // otherwise beep at slow interval
	       nextTime -= slowInterval;
	   }
	   audio.clip = grenadeBeep;
	   audio.Play(); // call Play only once
	}
	// Audio CountDown END  ####################################################################
}// END AudioCountDown()

Inspector> DRAG AND DROP the Bomb-Detonator SFX over var grenadeBeep

Play, click over the cube to start the SFX CountDown

For italian people: come funziona?
1. la variabile pinPulled viene settata true, corrisponde al togliere la sicura alla granata

2. fuseTimer è il conto alla rovescia che si attiva se pinPulled è true infatti:


//If a grenade's pin has been pulled, start the countdown
	if (pinPulled) {
	   fuseTimer -= Time.deltaTime;
	}
	else { // pin in place: reset fuseTimer and nextTime
	   fuseTimer = fuse;
	   nextTime = fuseTimer - slowInterval; // set time for 1st tick

3. fuseTimer una volta attivato viene scalato di 1 secondo alla volta

fuseTimer -= Time.deltaTime;

4. se è passato almeno un secondo…

if (fuseTimer <= nextTime)

5. avvia l’effetto sonoro

           audio.clip = grenadeBeep;
	   audio.Play(); // call Play only once

6. se il countdown è agli ultimi 3 secondi il suono sarà emesso più velocemente

if (fuseTimer <= nextTime) { // it's time to tick:
	   if (fuseTimer < 3.0){ // if entered fast range (last second), use fast interval
	       nextTime -= fastInterval;