UE Tip - Using Blueprint Interfaces to implement easy Usables
Implementing a bunch of doors or other interactable items in your world is a great opportunity to utilize Blueprint Interfaces. A BP interface simply defines a list of functions to be implemented by Actors that choose to implement the interface. In this case, there is just one function to implement: Use.
The general approach is to store a reference to the usable on your hero whenever your hero is in range of the object. Then, if the human players presses use while in range, the Use interface event is fired on your object.
Recipe Walkthrough: Create a new BP Interface called Usable with one method called Use. Any actor that can be used or opened should implement this interface. In blueprints, an interface is just a list of functions that a class cna implement.
Create a CurrentUsable variable of type Actor Reference on the Hero. This will be the actor that is called when the UseInput button is pressed. This lets you keep the input on the PlayerController or the Pawn. ( A negative pattern that I have seen often used it to try and capture input directly on the door. )
Back in the usable actor (eg door), implement the IUsable interface. This is done by selecting Class Settings, and adding the correct interface in the Interface section on the right-hand side. (See image below)
Also remember to implement an OnOverlap event for a collision component on your object - such as a collision sphere. In the overlap event, cast Other Actor to hero and set its CurrentUsable to self. Also implement the EndOverlap event and set CurrentUsable to null. In the image below, a message saying something like "Press E To Use" is also displayed.
Finally, implement the UseEvent interface event on your Usable Actor (e.g. Door). If the CurrentUsable is valid, then trigger Use event. Open the door, trigger the effect, consume the object,etc... The Use event can also optionally include a parameter for the instigator. This enables checks for inventory etc.
The last thing to do is to actually call our event when the proper input is pressed:
Once the hero has set this, if the human presses UseInput then this actor's Use event is called. The avoids us having to cast to the appropriate type in order to call the function.
At this point, any actor that implements the proper Use event, and BeginOverlap/EndOverlap is able to be triggered by the user.