Hey all,
I have a enemy detection system in place, i would like the enemy to play a one shot when the player is detected then switch to its chasing audio.
My problem is the PlayOneShot keeps playing over it self and is repeating.
That might happen because you keep detecting the presence of the player over and over, so you always get back to the detection sound. Do you have a playerDetected state store somewhere?
private AudioSource audioSource;
public AudioClip detectedSound;
public AudioClip chasingSound;
private bool playerDetected = false;
void Update()
{
if (PlayerIsDetected() && !playerDetected)
{
playerDetected = true; // Set flag to prevent sound from repeating
audioSource.PlayOneShot(detectedSound);
}
else if (!PlayerIsDetected())
{
playerDetected = false; // Reset flag when player is lost
}
else if (PlayerIsDetected() && playerDetected)
{
if (!audioSource.isPlaying) // Make sure the detection sound has finished playing
{
audioSource.clip = chasingSound;
audioSource.loop = true;
audioSource.Play();
}
}
}
bool PlayerIsDetected()
{
// Your enemy detection logic here
}