Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to detect if a player is within range of an enemy?

Discussion in 'Scripting' started by RayDawg, Feb 4, 2015.

  1. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    Currently, I'm trying to detect if a player is within range of an enemy which causes the enemy to give chase. Here is my code for detecting if the player is within range so far:

    Code (CSharp):
    1.         if(Vector3.Distance(this.transform.position, player.transform.position) <= AggroRange)
    2.         {
    3.             Debug.Log("Player in range");
    4.         }
    The statement is in FixedUpdate and yet nothing appears. Can someone please help?
     
    vinnyTeles likes this.
  2. tobyheadcast

    tobyheadcast

    Joined:
    Aug 5, 2014
    Posts:
    25
    Looks ok to me try debugging your range make sure you are getting close enough.


    Code (CSharp):
    1. float seperation = Vector3.Distance(this.transform.position, player.transform.position) ;
    2.  
    3. Debug.Log("Range to player = " + seperation  );
    4.  
    5. if(seperation  <= AggroRange)
    6. {
    7.             Debug.Log("Player in range");
    8.    
    9. }
     
    vinnyTeles likes this.
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,201
    If you're checking the distance every fixedUpdate, it's actually faster to use a trigger collider around the enemy that reacts to the player entering it.
     
  4. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    I want to avoid using trigger colliders because it feels very unwieldy. I did find out that the problem is that Vector.Distance isn't updating. I currently have the an instance of the enemy and the player both set to 10 units apart and no matter how close I move, Vector3.distance doesn't update the number.