Interaction script

Hey,

I have an “Interactable” script that has the interaction logic, this script is used for all the interactable objects (chest, doors, NPC etc), the way I’m using it is by having it as a component, and using Action events that my other classes can subscribe to

public event Action inRangeEvent;
public event Action outOfRangeEvent;
public event Action activateEvent;

My question is, is there a better, or simpler way to deal with a scenario like this, I’m still learning about Inheritance, Interfaces and Delegates, so far I’ve been using components over inheritance since it’s more intuitive to me. What I do works fine, but I’m looking for some feedback.

**Edit:**Gave the Interface method a try and it seems to work well, and it seems simpler than having to subscribe and unsubscribe to events. Some feedback on this would be appreciated.

I don’t know if I am understanding you question correctly, but you could just use
Distance = Vector3.Distance(transform.position, player.GameObject.transform.position); if (distancefromplayer <= maxdistanceeventcanoccur) { //code for event here }

From the comments, this Interactable script is sitting on the same GameObject alongside other scripts you intend to interact with. If that’s the case, then you can use interfaces to simplify things.

One nice part of interfaces is that you don’t actually care what the object is, only what it’s made of. In your case, you might consider making an interface with a bad name like IInteractable and requiring that your doors, keypads, light switches, etc all implement it:

// Forgive the double II naming, you already had an Interactable
// and the interface naming convention doesn't look great when the
// interface's actual name starts with I also
public interface IInteractable
{
    // Require that anything implementing this interface have a function
    // that looks like this
    void Interact();
}

public class Door : MonoBehaviour, IInteractable
{
    // Implement your interface, important that this is public as 
    // interfaces cannot require accessor keywords like public / private
    public void Interact()
    {
        Debug.Log("Door opened!");
    }
}

// Not sure what your class looks like
public class Interactable : MonoBehaviour
{
    // Cache whatever you should be interacting with
    private IInteractable interactableObject;

    void Awake()
    {   
        // GetComponent works with interfaces and other inheritance
        this.interactableObject = this.GetComponent<IInteractable>();
    }

    void Update()
    {   
        if (this.interactableObject != null && true /* some other condition */)
            this.interactableObject.Interact();
    }
}