sound will not always play.

So this script I’ve built, spawns an object…and if you click it, it should play a sound before it destroys.

This is only happening “sometimes”. Which is driving me crazy! I’m, not even sure how to debug this, as I’m new to Unity.

Here’s the script;

var resourceValue:	int 	= 	25;

var Countdown:		int 	= 	5;
var visible: 		float 	= 	0.50;
var invisible:		float 	= 	0.50;
var blinkFor: 		float	= 	5.0;
var startState: 	        boolean =	true;
var endState: 		boolean =	true;
var rayDistance: 	        float 	= 	0;

var clicked: 		AudioClip;

function Start () 
{
	animation.Play ();
	transform.position.z = -5;
    renderer.enabled = startState;
    yield WaitForSeconds(Countdown);
    
    var whenAreWeDone = Time.time + blinkFor;
    
    while (Time.time < whenAreWeDone)
    {
        if ( startState )
        {
        	renderer.enabled = false;
            yield WaitForSeconds(invisible);
            renderer.enabled = true;
            yield WaitForSeconds(visible);
        } 
        else
        {
            renderer.enabled = true;
            yield WaitForSeconds(visible);
            renderer.enabled = false;
            yield WaitForSeconds(invisible);
        }
    }
    renderer.enabled = endState;
    Destroy ( gameObject );
}

function Update ()
{
	var hit 	:RaycastHit;
	var ray 	= Camera.main.ScreenPointToRay (Input.mousePosition);
	var mainGUI = Camera.main;
 
    if ( Physics.Raycast ( ray, hit, 100 ))  
    {
      	if ( hit.collider.gameObject.renderer && Input.GetMouseButtonUp(0))
       	{
       		audio.clip = clicked;
			audio.Play ();
       		mainGUI.GetComponent(InGameGUI).resources += resourceValue;
       		Destroy (hit.collider.gameObject);
        }
   	}
}

I believe you should keep the object alive for the duration of the audio clip.

    audio.Play();
    Destroy( hit.collider.gameObject, audio.clip.length );