I’m trying to avoid using GetComponent as much as possible to avoid the associated performance hit so I’m looking for away around using it to damage targets in my game.
When an attacker performs an attack, I’m using Physics to check for any objects that might’ve been hit. Right now, I’m doing a simple small Physics.OverlapSphere where the weapon is in the world. However, this returns an array of colliders, which is next to useless to me as far as damaging objects. In order to damage all the objects hit, I would need to do GetComponent on every single collider returned to get my Entity objects which have the functions and properties necessary to incur damage. Are there any viable solutions to avoiding excessive use of GetComponent in situations like this?
My current (untested) solution is a system to lookup Entities by collider. I have an EntityManager that maintains two Dictionaries: one for (a numerical ID) and one for .
I get an entity from collider like this then:
I_Entity en = null;
foreach(Collider c in collidersHit)
{
if (c == attackingEntity.C_Collider)
continue;
if (c.gameObject.layer == attackerLayer)
continue;
if(EntityManager.GetEntityByCollider(c, ref en))
DamageControl.DamageController.Instance.AddDamageToTarget(en, 100f);
}
And the method returning the Entity looks like this:
public static bool GetEntityByCollider(Collider colliderAsID, ref I_Entity entityIn)
{
return entityByCollider.TryGetValue(colliderAsID, out entityIn);
}
I don’t know if this is the best solution or even a faster solution. Worse still, as of writing this, I don’t know that this even works. I haven’t had time to test it and it’s 2am currently.
I’d love any and all feedback or suggestions.