Best practice for interacting with elements of different nature

My question is about best practices in general, especially cheaper ways to interact in terms of memory cost.

I’m doing a 2D side-scrolling game using a very classic concept : my player can move left and right, and will interact with all kinds of elements, such as enemies, non-player characters, items, weapon stores, switches… well, all the usual stuff.

All kind of interactions can happen depending on the elements’ nature : some npc will talk to the player or give him stuff (money, ammo, items etc), enemies will chase and hit him, switches will trigger devices, etc.

For the technical part, it relies on trigger collision detection.

I hesitate between two ways to implement these interactions (I assume there are many others). Both of them seem to work, but I wonder if one of them is better and cheaper.

The first one consists in checking the tag of the colliding element, then sending it a message.
My player’s code would look like this :

    private void OnTriggerEnter2D(Collider2D collision) {
        string tag = collision.tag;
        if (tag == "Enemy" || tag=="Npc" || tag=="Switch" etc…) {
            collision.SendMessage("Interact");
        }
    }

The second one would analyze the colliding element’s components, then call its Interact() method (assuming each of these elements have one).

Rather than looking for several components (such as an Enemy.cs script, a Npc.cs script, a Switches.cs script etc), I thought of creating an Interface shared by these elements (or maybe an Abstract class, not quite sure).

My code would look like :

private void OnTriggerEnter2D(Collider2D collision) {
    // Interactable is the name of my interface or abstract class
    Interactable inter = collision.GetComponentInChildren<Interactable>(); 
    if (inter != null) {
        inter.Interact();
    }
}

All advice will be appreciated.

Honestly, from a coding standpoint, it’s much easier to use an interface instead of comparing tags and running specific methods, since as your game scales, youll have hundreds of tags. Its definitely the nicer way to do it in terms of readability. Coming back to a project that has lots of tags and layers unnecessarily, only adds to the hastle.


Performance-wise, there’s nothing wrong with inheritance or using objects on a high level. If you dont see any visible problems with your memory or speed, dont worry about it.