- Home /
Need help using overlap sphere
I am having trouble trying to figure out how to make it so when an enemy is in the radius of a tower it will start taking damage, iv found other topics asking similar questions but I didn't quit get them and I am hoping out at least how to use Overlap Sphere?
Using overlap sphere can cut fast into performance, maybe u can put a circle/sphere(based on 2D/3D) collider on your object and make it a trigger, then u can do your stuff in the on trigger enter event, its easier and better for performance. (You can have multiple colliders, if you add an empty gameobject to your object and add the collider on that one)
Answer by Favouriteless · Feb 13, 2020 at 11:13 AM
Honestly, I suggest not using OverlapSphere as it is very performance heavy. If you really want to, see @ctjagielski 's answer.
As for the other approach, would keep a list of all enemies and use (tower.position - enemy.position).sqrMagnitude < tower.range (range should be squared on start) to compare the distances of enemies from the tower. I do this in the tower defense game I am currently developing and it made a huge performance impact.
Using an ArrayList to keep track of enemies will do, add any enemies to the ArrayList in their Start() method and remove them when they die.
Very good advice I$$anonymous$$HO - just because Unity makes things like this function, and colliders even, available does not mean you need to or should use them.
As an example, I came across someone once who needed a strictly cylindrical collider, and implemented it by using the overlap of a box collider with a capsule collider.
The thing was, they only had one ball they needed to know about, and the cylinder was always aligned with the y axis.
What with the extra colliders and overlap code they needed to make events fire only when the ball was in both colliders, it ended up being ridiculously slow compared to just looking at the horizontal (squared) distance of the ball from a point, together with testing its y coordinate for the height.
Answer by ctjagielski · Feb 12, 2020 at 01:27 PM
If you're using 3D, use this:
Physics.OverlapSphere returns an array of colliders within the given radius, from a defined center point.
For this I'd use transform.position for center, and you may need to try a few times to get the radius right. You can use OnDrawGizmos to view the size of the radius in the scene view, just make sure Gizmos are enabled.
public float radius;
private void Update ()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);
for (int i = 0; i < hitColliders.Length; i++)
{
GameObject hitCollider = hitColliders[i].gameObject;
if (hitCollider.CompareTag("Enemy"))
{
//add damage
}
}
}
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere (transform.position, radius);
}