check if player is close

hay please i want my AI to call the attack script if the player is 3m from him when his moving around the way points.

using UnityEngine;
using System.Collections;

public class GoingToWayPoints : MonoBehaviour {

	public Transform targetplayer;
        public int PlayerDistance = 3;

public const float ARRIVE_DISTANCE = 3f;
public float speed = 5.0F;

private GameObject targetGO;
private WaypointManager waypointManager;
	
private void Awake(){
	waypointManager = GetComponent();
	targetGO = waypointManager.NextWaypoint(null);
		}

private void Update () {
	transform.LookAt( targetGO.transform );
	float distance = speed * Time.deltaTime;
	Vector3 source = transform.position;
	Vector3 target = targetGO.transform.position;
	transform.position = Vector3.MoveTowards(source, target, distance);

	
if( Vector3.Distance( source, target) < ARRIVE_DISTANCE){
		targetGO = waypointManager.NextWaypoint( targetGO );
	   }
		
	}
  }

void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
targetplayer = go.transform;
}

}

2 Answers

2

You should have each AI know about the player, like so:

// retrieve the player GO
void Start() { player = GameObject.Find("Player"); }

void Update() { 
  if ((player.transform.position-this.transform.position).sqrMagnitude<3*3) {
    // the player is within a radius of 3 units to this game object
  }
}
private GameObject player;

Use Physics.Raycast Method to detect objects at distance of the player.

void Update() {
        RaycastHit hit;
        if (Physics.Raycast(transform.position, Vector3.forward, out hit))
            float distance = hit.distance;
           if(distance==3){
          // execute your code here
          }
 }

More Examples
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html