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?
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.
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*.gameObject;*
if (hitCollider.CompareTag(“Enemy”))
{
//add damage
}
}
}
void OnDrawGizmosSelected ()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere (transform.position, radius);
}