Play sound when enemy is visible on the screen?

Hi, I know this question has been asked a thousand times already but the scripts given in the answers don’t work like I want them to…

I know Renderer.IsVisible and other things do trigger something when an enemy is visible but if the enemy is behind a wall and you look at that wall it is still counting as visible which I don’t want.

Basicly I want to make a jumpscare just like in the Slender game when you look at him. (No I’m not making a Slender game!)

I have made a script ( Not entirely made by me, just copied and pasted some codes from random sites I found and mixed them together to make it do what it does now :stuck_out_tongue: BTW I’m next to nothing at scripting so please make the answer as simple as possible :slight_smile: ) I posted here that plays a sound when the enemy is in the middle of the screen but I want the sound to play when the enemy is visible from anywhere on the screen.

In short:

Is someone able to edit my script so it plays the sound when an enemy is visible anywhere on my screen but it doesn’t play the sound when the enemy is behind a wall?

This is my script:

var jumpscareSound: AudioClip; // Sound that plays when enemy is in the middle of the screen

var interval:int; // Interval = X seconds before the sound can be played again if enemy is in the middle of the screen.

private var onetime = false; // If true, interval is busy.

function Update() {

var hit: RaycastHit;
var forward = transform.TransformDirection (Vector3.forward );

    if (Physics.Raycast (transform.position, forward, hit))


 Debug.Log("Enemy in middle of screen, playing sound now!"); 
if (!onetime)
    onetime = true;

 Debug.Log("No enemies in the middle of your screen :)");


 Debug.DrawLine (transform.position, hit.point,Color.white);


function soundInterval() {

yield WaitForSeconds(interval);
onetime = false;


I would give this a shot. It would require attaching a sphere collider to your camera/player, setting it as a trigger, and setting it’s radius to the distance that you want to check within. Essentially, it tracks enemies within the trigger range and casts a ray to them each frame. Whenever it does detect that it hits an enemy it fires a message to it and removes it from the list. You can comment out the list removal and handle a timer on the enemy side if you want.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyChecker : MonoBehaviour
	private List<GameObject> enemies = new List<GameObject>();
	void OnTriggerEnter(Collider other)
		if (other.tag == "Enemy")
	void OnTriggerExit(Collider other)
		if (other.tag == "Enemy")
	void Update()
		RaycastHit hitInfo;
		foreach (GameObject enemy in enemies)
			Ray ray = new Ray(transform.position, transform.position - enemy.transform.position);
			if (Physics.Raycast(ray, out hitInfo))
				enemy.SendMessage("OnVisible", SendMessageOptions.DontRequireReceiver);