PLay the scary sound when monster is front of me. HELP (C#)

Hello! So im develoing a horor game like slenderman and I want to play sound effect when monster is front of me. How I can do that? I have a sound script like this:

if (Vector3.Distance(transform.position, player.position) <= 30)
        {
            yakın = true;            
            sesOyna = true;
            if (sesOyna == true)
            {
                if (Time.time > clipEnd)
                {
                    AudioSource.PlayClipAtPoint(aniKorku, player.position);
                    clipEnd = Time.time + aniKorku.length + 5;
                }
            }
        }

But its play the sound effect when he is near me even the monster is behind me.

You need to check whether the monster is inside the camera frustum. Have a look at this link and read up about it.

  • Using an if statement, check if the monster is visible by the camera
  • Check if the monster is within the certain distance
  • Play sound/music/etc.

For performance reasons I don’t know if checking that the monster is visible by the camera is efficient enough to be called constantly, or mathf.distance is better to be called constantly.

Thanks alot! I will check it.

Can u give an example please… Because there is no example in unity scripting refence.

You could replace this:

if (Vector3.Distance(transform.position, player.position) <= 30)

With a forward raycast.

I assume this script is not on the player so what is it on.

I think the easiest would be to check if the angle of the “transform.forward” and the monster position-player position, like this:

public float FOV; //field of view of camera

if(Vector3.Distance(transform.position, player.position) <= 30   Vector3.Angle(player.forward,transform.position-player.position) <= FOV)
{
//Do the rest
}

Altough this ignores walls and things like that. If you need that, then a raycast would be better.

Using field of view is easy and useful! Thanks too much :slight_smile: