play sound when enemy is apear

Hi… i have this script to play sound when enemy is apear…

var appear:AudioClip;
function OnBecameVisible() {
    enabled = true;
    audio.PlayOneShot(appear);
}
function OnBecameInvisible () {
    enabled = false;
    audio.Stop();
}

it works… but when enemy is staying behind the wall script playing the sound too…and i dont want this…
how to fix it?

You might want to use something like :

renderer.isVisible

This basically works the same, and when your enemy gets behind the wall the audio should stop.

public GameObject enemy;

void Update() {
if(enemy.renderer.isVisible) {
audio.PlayOneShot(appear);
else {
return();
}
}
}

Something like this should work.

-Tim

thanx but it makes error: Unexpected symbol ‘else’… why? :open_mouth:

edit…: fixed… but dont work… :confused:

audio.PlayOneShot(appear);

The way this function works is that it instantiates a new audio source object that is a copy of the audio object. It than sets that object to play and destroys it after the clip finishes.

If you would like to stop the clip when the enemy is no longer visible you should have the audio source be a component and play / stop it manually based on the render state.

function OnBecameVisible() 
{
    enabled = true;
    audio.Play();
}
function OnBecameInvisible () 
{
    enabled = false;
    audio.Stop();
}