Detecting Distance from Object at any polint

I’m terrible with math-related coding, so I could use some help on this. Currently my enemy AI detects players or objects it can fight using colliders, the problem is that enemy attempts to fight something in it’s collider without actually moving in position toward the object it should be fighting. If I have the enemy move to the gameobject it should fight, it will stand right on top of the object of course.

I’d like to be able to set a range of where the enemy should stand before attempting to attack, but I’m unsure how to do this.

You need to give your unit some form of an attackDistance property. This will also indicate whether this object is ranged or melee. When your OnTriggerEnter detects an incoming collider, check whether this is an enemy. Typically, attackRadius > attackDistance for melee. That said, a melee AI will become aggressive to an enemy once it enters e.g. 50 distance (attackRadius), but as a melee, the distance it will actually fight is 5 (attackDistance).

Thus, once an enemy collider enters the attackRadius, check the Vector3.Distance between the positions of the colliders’ transforms. This will return a float which you can compare to your attackDistance. If the found value is greater than attackDistance, then fire an IEnumerator with a while loop; in the while condition, keep checking if the distance between your two colliders is greater than attackDistance. Once it becomes equal, the loop will exit, which is when you can launch your attack (I assume a method you call). As this is AI, the attack method could be launched by means of InvokeRepeating. Inside of this method, keep checking for the distance and if it becomes greater than attackDistance, rerun the coroutine and CancelInvoke of the attack method.

This is not the only solution; it is heavily influenced by your development design, but this is how I would approach it.