There is no renderer attacked to main camera

Hi!

ok, so im trying to detect if a gameobject is outside the view of the main camera of the character controller. Here is my script, it is attached to the enemy:

var angel : Transform;
var cam : GameObject;
var target : Transform;

function Start () {

}

function Update () {
	var rot = target.position - angel.position;
	var dist = Vector3.Distance(angel.position, target.position);
	rot.y = 0;
	
	if (cam.renderer.isVisible) {
		//do nothing
	} else {
		Debug.Log("Not looking");
	}
}

Here is the actual error I get:

alt text

Now, obviously I do have a renderer attached to my cam object, it is the main camera.
This is driving me up the walls, any ideas?

You’re using isVisible wrong: you should check the target’s isVisible property instead of the camera’s (even because the camera usually has no renderer…)

But renderer.isVisible actually only tells whether the object is inside the viewing angle of any camera, and will be true even if it’s completely obscured by dozens of other objects, mountains etc. If you want to know whether the angel can see the target, the test should be different:

  var hit: RaycastHit;
  if (Physics.Linecast(angel.position, target.position, hit) && hit.transform == target){
     // there's a clear line of sight between angel and target
  }

If you have only one camera and it’s attached to the angel, you could also use isVisible in order to make sure the target is inside the angel viewing angle:

if (target.renderer.isVisible){ // if target inside viewing angle...
  var hit: RaycastHit;
  if (Physics.Linecast(angel.position, target.position, hit) && hit.transform == target){
     // there's a clear line of sight between angel and target
  }
}

If the enemy doesn’t have a camera, or if there’s more than one, check the angle between the enemy’s forward direction and the target direction instead:

var dir = target.position - angel.position;
if (Vector3.Angle(dir, angel.forward) < 60){ // visibility is 60 degrees in any direction
  var hit: RaycastHit;
  if (Physics.Linecast(angel.position, target.position, hit) && hit.transform == target){
     // there's a clear line of sight between angel and target
  }
: