How to Add a Detection Range to enemies

I am trying to make an rpg and I was wondering if there was a way to make Enemies have a range so that if a player were in that range, the enemy would attack them. Please Help me as soon as possible.

-SK

3 Answers

3

Hi, you can use simple code:

 C#
    public float range;
    public Transform player;

Update()
{
   if(Vector3.Distance(player.position, transform.position) <= range)
   {
   //go to player
   }
}

That’s simple solution, then you can use an trigger in player so enemy can attack him when hit trigger sphere.

Thanks for the answer. I really appreciate it!!

Awesome!!!

Thank you sooo much!! i needed to make a few changes tho but it worked!

This comment is already 5 years old but I just want to say thank you so much!! Had to go through sooo many video tutorials and this was the perfect solution. Thanks man! Have a great day.

How to use this if an obstacle comes between the player and the enemy?

One of the possibilities is to use sphere or circle trigger collider.

  1. Add child object

  2. Add rigidbody or rigidbody2d

  3. Add circle or sphere collider to it, set isTrigger=True

  4. Add onTrigger events handler to this child

    void OnTriggerEnter2D(Collider2D other) {
    	if(transform.parent && transform.parent.gameObject != other.gameObject)
    		Debug.Log (transform.parent.gameObject.name + ": I can see " + other.gameObject.name);
    }
    

Spherecast comes to mind. If you do a Vector3.distance you might want to do a raycast to see if the enemy can see your player. So you don’t get detected through walls and doors or whatever.

So your prefab is instantiating a gameobject whose child will be body?