Physical buttons/toggles; is there a clever way?

So I’m trying to make a game where (among other things) the player can run around and hit switches (like, physical buttons in the game world) to trigger events. The method I devised for doing this is basically as follows:

a) Every collider in the game world has the script “interactions,” which contains a number of booleans like ‘grabable’ ‘toggleable’ ‘pressable’ etc., as well as a target gameobject (usually null, unless it’s a switch/button).

b) The player has the script “interact.” In this script, whenever the player presses E, it raycasts and grabs the collider the player is facing, then looks at the “interactions” script associated with that collider. If the boolean ‘grabable’ is true, the player picks up the item, etc.

c) If the boolean ‘pressable’ is true, then the script will run the subroutine “Activated” in the target gameobject.

d) The “Activated” subroutine is unique for each game object. Thus, I can have a interaction script which, depending on what it is linked to, could open a door, turn on a machine, etc.

The problem with this is that I can’t have a script with the same name do different things in different game objects (at least I haven’t been able to figure out how). What this means is that each button needs a unique protocol for triggering things, which in turn means that I can’t have a generic “interactions” script for all objects. I could do this with by attaching something like “OnMouseover {if Buttondown…}” to every button, but that feel so much less elegant; not only does this require a unique script for every object, but now every interactable item will constantly be searching for the mouse. It seems much better to just raycast when E is pressed, but then I need some sort of universal response script. What I want is something like ‘OnTrigger,’ but that’s only for physical object collisions, isn’t it?

You have a couple of options off the top of my head…

  1. As @Sinn stated, you could create a base InteractionScript with an abstract method of abstract protected Interact(GameObject interacter), then either create a unique script per interactive object; or, create simple scripts like GrabInteraction, DamageInteraction, etc… that inherits off the InteractionScript (with a liberal amount of public properties to change behaviors [this is what unity does]).

  2. Another option is to assume every object has a method called Interact on it, and call SendMessage of the GameObject of the Ray Casted Collider. Just ensure you have SendMessageOption.DontRequireReceiver set, so it doesn’t throw an exception.

One nice thing about the SendMessage is that it will call Interact on every Script attached to the GameObject at once.

Alternatively you would call GetComponents and foreach Interact with the first option.