I expect that the part you want to optimize is collision.collider.name.Equals("") because you used the Unity profiler and found out that this particular line of code takes up a considerable amount of execution time. You also only might just want to find out if the other object is friend, enemy or neutral.
Let's also assume that you have more than two factions in your game. Because if you only have players and enemies, you don't need an enum to store faction membership. A bool would be much simpler.
In order to do that, you could add a component FactionMembership to each object in your game (or at least those where the friend/foe status is relevant). That class could include an enum with all the factions the object belongs to:
public FactionMembership: MonoBehaviour {
public enum Faction {
CATS,
DOGS,
HAMSTERS
}
public Faction faction;
}
When you add this component to a GameObject, you will have a dropdown menu in its inspector where you can pick the faction it belongs to between "CATS", "DOGS" and "HAMSTERS".
Now back to your collision function. I assume you want to find out if the object belongs to a different faction. In that case you would do this:
private void OnCollisionEnter2D(Collision2D collision)
{
// get the faction membership components of both objects.
// note: if you call this function a lot, you might want to
// store myFactionMembership in a private class-level variable
// which you read in Start to improve performance
FactionMembership myFactionMembership = GetComponent<FactionMembership>();
FactionMembership otherFactionMembership = collision.gameObject.GetComponent<FactionMembership>();
// do both objects in this collision actually have a faction membership?
// If not, then we are not interested in this collision.
if(myFactionMembership == null || otherFactionMembership == null) {
return;
}
// check if we have encountered an enemy
if (myFactionMembership.faction != otherFactionMembership.faction) {
Console.log("Enemy encountered!");
}
}
This code of course assumes that all 3 factions we have in this game are mortal enemies who will always fight each other. But this might not always be the case. For example, what if the dogs and the hamsters have fored an alliance against the cats? In that case it might make sense to add a helper method IsEnemyOf(FactionMembership other) to FactionMembership.
How that function determines who is allied with whom is outside of the scope of this answer.
FactionMembership myFactionMembership = GetComponent<FactionMembership>();
FactionMembership otherFactionMembership = collision.gameObject.GetComponent<FactionMembership>();
if(myFactionMembership == null || otherFactionMembership == null) {
return;
}
if (myFactionMembership.IsEnemyOf(otherFactionMembership)) {
Console.log("Enemy encountered!");
}