How to make an universal action button script

Press E to open a door, turn on a radio, pick up a thing, talk to that guy… The button that does it all. My problem is writing the script. I though about using delegates, events, inheritance, or abstracts in the Interact script so it can work with any named script that has the universal function in order to interact. If this universal function is called, then it executes whatever is inside, like the OnTriggersXXX, OnCollisionXXX, OnMouseClick… But I don’t have the know-how to do this. Is this right way to go? Is there something better?

If it’s a First Person Camera, you can use Raycast when the action button is pressed and call a script that activates a UnityEvent that holds the action for that object. If it is 3rd Person, same principle but instead of Raycast use Triggers. OnTriggerEnter set the interactable object in the player script and unset OnTriggerExit. Call the interactable object when the action key is pressed.

The Interactable Objects will use a script like this:

using UnityEngine;
using UnityEngine.Events;
 
public class ActionObject: MonoBehaviour {
     public UnityEvent myUnityEvent;
 
     void Awake() {
         if (myUnityEvent == null)
             myUnityEvent = new UnityEvent();
     }
 
     public void DoAction() {
         myUnityEvent.Invoke();
     }
 
 }

First Person Player

using UnityEngine;
 
public class FirstPersonPlayer: MonoBehaviour {
     public Camera camera;

     void Update() {
         if(Input.GetKeyDown("E"))
         {
             //Raycast
             RaycastHit hit;
             Ray ray = camera.ScreenPointToRay(Input.mousePosition);
    
             if (Physics.Raycast(ray, out hit)) 
             {
                  GameObject objectHit = hit.transform.gameObject;

                  //Try getting ActionObject Component from the retrieved object
                  ActionObject actionObj = objectHit.getComponent<ActionObject>();

                  if(actionObj!=null)
                  {
                       //if ActionObject is found call DoAction()
                       actionObj.DoAction();
                  }
              }

         }
     }
 
 }

3rd Person Player

using UnityEngine;
 
public class ThirdPersonPlayer: MonoBehaviour {
     public ActionObject actionObj;

     void Update() {
         if(Input.GetKeyDown("E"))
         {
             if(actionObj!=null)
             {
                  actionObj.DoAction();
             }
         }
     }

     void OnTriggerEnter(Collider other) {
              //Try getting and setting ActionObject Component
              actionObj = other.gameObject.getComponent<ActionObject>();
     }

    void OnTriggerExit(Collider other) {
              //unset the actionObject
              actionObj = null;
     }

 }

You can work from here and customize those scripts to fit your needs.

I made a package with the scripts and samples. It can be downloaded in my website http://www.fenika.net/?p=7