Skip to content
This repository was archived by the owner on Oct 19, 2020. It is now read-only.

Interfaces

pixeltris edited this page Jun 9, 2019 · 5 revisions

This covers some additional scenarios for interfaces. See Exposing C# defined types to UE4.

Interfaces can be used to provide a set of functions which can be implemented by multiple C# or Blueprint defined types. As C# needs to implement all interface functions, there are some slightly different requirements compared to C++ interfaces.

All UE4 exposed interfaces are limited to UE4 exposed functions only. You cannot add non exposed functions. The reason for this is that a default implantation is generated which directs function calls where a Blueprint implements an interface.

In the following example the interface IMyInterface is exposed with 1 function which is a BlueprintImplementableEvent. The function body in UMyObj.MyFunc1 will get overwritten by AssemblyRewriter.exe to redirect the function call to any potential Blueprint which inherits from the class.

[UClass]
class UMyObj : UObject, IMyInterface
{
    protected override void BeginPlay()
    {
        base.BeginPlay();
        FMessage.Log(ELogVerbosity.Log, "Hello " + MyFunc1());
    }

    public int MyFunc1()
    {
        throw new NotImplementedException();
    }
}

[UInterface]
interface IMyInterface : IInterface
{
    [UFunction, BlueprintCallable, BlueprintImplementableEvent]
    int MyFunc1();
}

In this example the situation is the same, but the function is defined as BlueprintNativeEvent. We must define both the function MyFunc1 and MyFunc1_Implementation. The code should be written inside the _Implementation function (as MyFunc1 will be re-written in the same way as the first example).

[UClass]
class UMyObj : UObject, IMyInterface
{
    protected override void BeginPlay()
    {
        base.BeginPlay();
        FMessage.Log(ELogVerbosity.Log, "Hello " + MyFunc1());
    }

    public int MyFunc1()
    {
        throw new NotImplementedException();
    }

    public int MyFunc1_Implementation()
    {
        return 100;
    }
}

[UInterface]
interface IMyInterface : IInterface
{
    [UFunction, BlueprintCallable, BlueprintNativeEvent]
    int MyFunc1();
}

In this example we don't implement an interface, but it's still possible to access IMyInterface if Blueprint inherits from our class and implements the interface.

[UClass]
class UMyObj : UObject
{
    protected override void BeginPlay()
    {
        base.BeginPlay();
        IMyInterface myInterface = GetInterface<IMyInterface>();
        if (myInterface != null)
        {
            FMessage.Log(ELogVerbosity.Log, "Hello " + myInterface.MyFunc1());
        }
    }
}

[UInterface]
interface IMyInterface : IInterface
{
    [UFunction, BlueprintCallable, BlueprintImplementableEvent]
    int MyFunc1();
}
Clone this wiki locally