delay timer on sound never counts down more than 0.02 C#

I’m a newbie so appologises in advance. I added a simple timer to allow an audioclip to play out before destroying the gameobject but it never counts down more than 0.02 seconds so my gameobject is never destroyed. Here’s the code…

`public float timedDelay = 0.5f;

public int pointValue;


void OnCollisionEnter(Collision collision)
	{

	   if (collision.collider.tag == "Bullet") 
		{
		Debug.Log ("hit by bullet");

		audio.Play ();
		timedDelay -= Time.deltaTime;
						
		if (timedDelay <= 0.0f) 
		{
				
		scoreManager.Score += pointValue;
					
		Destroy (gameObject);
		}

	}

}

`

Pardon me if I mucked up the markdown :slight_smile: I restate, I’m a newbie :slight_smile:

Hey there, welcome to the Unity Community!

The error in your code is that the part where you manage time is only called once.

Follow the lines of code.

Your collider is hit by a bullet, and the message is logged out.
Some audio is played.
timeDelay goes down by Time.deltaTime (0.02 seconds for you currently)
then if timeDelay is less than 0, it is destroyed.

That’s it. Time Delay was only reduced once.

Solution?

Well firstly, moving all this:

       timedDelay -= Time.deltaTime;
 
       if (timedDelay <= 0.0f) 
       {
 
       scoreManager.Score += pointValue;
 
       Destroy (gameObject);
       }

into an Update function, would do the trick, though you would need to check whether it has been hit yet. You could have a boolean called isDead, and set isDead to true when they are hit by the bullet, and the in the update function, check if isDead is true. If so, do that code above.

Alternatively, you could make use of the WaitForSeconds function. If you include this function in your code:

IEnumerator ClipComplete(AudioSource source)
{
	yield return new WaitForSeconds(source.clip.length);

	Destroy(gameObject);
}

You could then simply use this line of code to destroy the object after the clip is complete:

StartCoroutine(ClipComplete(audio));

If you have any further questions I’m happy to help, just use the comments :slight_smile: