# Implementing an interaction system that can perform different tasks dependant on the object you are trying to interact with?

In No Mans Sky there are objects to interact with in the world and the result of the interaction changes depending on the object. For example, if you interact with a plant it will give you resources but if you interact with the save point it will save the game. I was wondering if it would be efficient to add an 'Action' class that had different methods for each different action (save(), grab resources(gameObject)), then call each action depending on what object you are interacting with...

Another possible solution I came up with is to have a base class of 'Action' and have each action as a script that inherits from this class, then attach them as a component to the interactable objects. Then have the interaction system check if it has an 'Action' script and perform that action if required.

I am just wondering if any of my solutions would be effective, or if there is a much simpler way around this problem that I am missing.

I would implement this with an abstract base class Interactable which inherits from MonoBehaviour and has an abstract method public abstract void Interact(Player player).

Any object the player can interact with would then have a component which extends that abstract base-class and provides an object-specific interaction method.

To call that method form the player-class, use:

Interactable interactable = otherObject.GetComponent<Interactable>();
if (interactable != null) interactable.Interact(this);


GetComponent also returns components which inherit from the provided class, so it will give you any component which extends Interactable.

Another option is to use Unity messages. When the player tries to interact with an object, call otherObject.SendMessage("Interact", this) to send an "Interact" message to all components of the object. This will call a method "Interact" on any component of that object which has one. The nice thing about this is that you can have any number of components on an object which handle interactions.

The Command Pattern seems like it would be useful here. First I'd classify the various types of interactions, associating each interaction with a command slot on your desired object. With this setup you can add command instances to and remove command instances from these slots on the object based on the state of the game. This approach is pretty flexible and dynamic as you can swap out commands so that the object can respond in different ways to a given type of interaction.