Attack Enemy if looking at C#

Hi Everyone, I’m putting together a attack enemy script. I was wondering is there a function that if the player’s camera is looking at the enemy it does a certain function? I think it would look something like this.

if(Camera look at enemy){
AttackEnemy();
}

You could use a variety of methods to accomplish this. One being raycasting, where you raycast forward from the camera, if the raycast hits an enemy, detect how far the enemy is with Vector3.Distance() and if they are within range, trigger your method for autoattacking. Another way would be to use WorldToViewportPoint(enemy.transform.position) to detect if the enemy is visible on the screen at all and go from there.

Here is what I have, you’ll have to create variables though, like attackrange and spotAngle

public void CheckforTarget2 (){
		 		
		
		var forward = transform.TransformDirection(Vector3.forward);
		var distance = Vector3.Distance(transform.position, enemy.position);			
		var targetDirection = enemy.position - transform.position;
		targetDirection.y = 0;
		var angle = Vector3.Angle(targetDirection, forward);
			
		// Start shooting if close and player is in sight
		if (distance < attackRange && angle < spotAngle)
		{
			Shoot(); //or attack or whatever

		}
	}

If there is an enemy in front, or slightly to the side(depends on spotAngle) amd hes in range then we shoot. This is from the fps tutorial.

Funny thing is, I forgot to change all the “var” stuff to the c# way of doing things, and yet it still works in my AI’s c# script