audio clip play slow an laggy

Hello ,
I have a problem with playing an audio clip when the object set to active .I want to get my object active when the player score reach 100 . Until here , everything worked great . So if the object has set to active , the sound should play . But it play with lag and too noisy sound!.

Here is my script :

using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class ActiveGame : MonoBehaviour {
	public Score scoreScript;
	public  float ScoreToEnable;
	public AudioClip EnableSound;
	public GameObject Desstroy;
	// Use this for initialization
	void Start () {

		//Find Scripts GameObject, and get Score Component.
		scoreScript = GameObject.Find ("Score").GetComponent<Score>();

	}
	
	// Update is called once per frame
	void Update () {

		if(scoreScript != null && scoreScript.score >= (ScoreToEnable))
			Desstroy.gameObject.active = true;

		if(scoreScript != null && scoreScript.score >= (ScoreToEnable))
			audio.Play();
			audio.Play(22050);

	}
}

Please Note that : I’ve tried to use audioclip play at point , audio.play , and audio play oneShot . Nothing worked !.

Please Help !

1 Answer

1

You’re starting the sound every frame in Update, and this produces a really annoying sound! You should somehow make sure that the sound is played only once when the conditions are satisfied - using a boolean, for instance. There are also errors in the if statements: when the if condition is true, only the statement that follows it is executed. If you want to execute more than one instruction, make a “compound statement”: enclose the instructions in curly brackets, like below:

...

private bool scoreReached = false; // declare this outside any function

void Update () {
    if (!scoreReached && scoreScript != null && scoreScript.score >= ScoreToEnable)
    { // enclose the code in curly brackets like this
         Desstroy.SetActive(true); // active is obsolete, use SetActive instead
         audio.Play(); // play the sound
         scoreReached = true; // make sure this code won't execute anymore
    }
}

Great answer sir ! :) Thank you :) .