Chapter 7. Communication between Classes and Interfaces

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:

  • Creating a UInterface
  • Implementing a UInterface on an object
  • Checking if a class implements a UInterface
  • Casting to a UInterface implemented in native code
  • Calling native UInterface functions from C++
  • Inheriting UInterface from one another
  • Overriding UInterface functions in C++
  • Exposing UInterface methods to Blueprint from a native base class
  • Implementing UInterface functions in Blueprint
  • Creating C++ UInterface function implementations that can be overridden in Blueprint
  • Calling Blueprint-defined interface functions from C++
  • Implementing a simple interaction system with UInterfaces

Introduction

In 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181