C++ UInterface cast failing and other problems

This is the guide I’ve followed: Interfaces | Unreal Engine Documentation
Being updated to Ue 4.14 I suppose it’s better to follow than 2 years old tutorials.

My Interface


// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "InteractiveInterface.generated.h"

// This class does not need to be modified.
UINTERFACE(Blueprintable)
class UInteractiveInterface : public UInterface
{
	GENERATED_BODY()
};

/**
* Tutorial: https://docs.unrealengine.com/latest/INT/Programming/UnrealArchitecture/Reference/Interfaces/
*/
class MID_API IInteractiveInterface
{
	GENERATED_BODY()

		// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
	UFUNCTION(BlueprintNativeEvent, Category = Gameplay)
		void Execute(UObject* caller, UActorComponent* component = nullptr, int interactionType = 0);

	virtual void Execute_Implementation(UObject* caller, UActorComponent* component = nullptr, int interactionType = 0);
};


Where I use it:


AActor* result = RayCastForObject();

	if (result != nullptr)
	{
		
		if (result->GetClass()->ImplementsInterface(UInteractiveInterface::StaticClass()) )
		{
			IInteractiveInterface* interf = Cast<IInteractiveInterface>(result);
			interf->Execute(this);
			return true;
		}
	}
	return false;

First Issue: I cannot a BlueprintActor that implements the interface.

Second Issue: if I use the C++ Actor class that implements the interface or its derived blueprint the cast works but I cannot call the function Execute(). I can call Execute_Execute() but it doesn’t use default parameters.

Don’t call the function Execute, because that will make life difficult.

The first parameter of Execute is the object you’re calling the function on. In your case:



interf->Execute_MyFunction(interf, this);


Casting won’t work when the interface is added at the blueprint level. It can’t, because the object doesn’t actually derive from IWhateverInterface at the C++ level at all.
The most generic way that works with objects implementing the interface in both C++ and Blueprint, is to call the execute function statically. No need for an interface pointer, just take an object, check it implements the interface, then do:


IWhateverInterface::Execute_SomeFunction(Object, Parameters...);

And yeah, it probably won’t duplicate the default arguments. Not really a big deal, default arguments are mostly evil anyway.

3 Likes