This chapter shows you how to write your own UInterfaces, and demonstrates how to take advantage of them within C++ to minimize class coupling and help keep your code clean. The following recipes will be covered in this chapter:
UInterface
UInterface
on an objectUInterface
UInterface
implemented in native codeUInterface
functions from C++UInterface
from one anotherUInterface
functions in C++UInterface
methods to Blueprint from a native base classUInterface
functions in BlueprintUInterface
function implementations that can be overridden in BlueprintIn your game projects, you will sometimes require a series of potentially disparate objects to share a common functionality, but it would be inappropriate to use inheritance, because there is no "is-a" relationship between the different objects in question. Languages such as C++ tend to use multiple inheritance to solve this issue.
However, in Unreal, if you wanted functions from both the parent classes to be accessible to Blueprint, you would need to make both of them UCLASS
. This is a problem for two reasons. Inheriting from UClass
twice in the same object would break the concept that UObject
should form a neatly traversable hierarchy. It also means that there are two instances of the UClass
methods on the object, and they would have to be explicitly differentiated between within the code. The Unreal codebase solves this issue by borrowing a concept from C#—that of an explicit Interface type.
The reason for using this approach, instead of composition, is that Components are only available on Actors, not on UObjects in general. Interfaces can be applied to any UObject
. Furthermore, it means that we are no longer modeling an "is-a" relationship between the object and the component; instead, it would only be able to represent "has-a" relationships.
3.143.4.181