Download

How to call a Blueprint Interface from C++?

I have a Blueprint interface, say HelloInterface, with a method Hello() on it.
I spawn this as an AActor from C++ (via World->SpawnActor).
How do I go about calling Hello() after I got my actor instance? Do I need to declare a counter-part interface on C++ side and somehow match them together?

p.s. I did find some sources online seemingly doing what I need, but I can’t quite grasp what they are doing, so please bear with me here, as I may need to ask follow-up questions. Thank you!

As far as I know you can’t call blueprint functions from C++. You should declare the interface in C++, if you want to use it with C++.

I was able to figure out a way that is not exactly what I expected, but very close and works for my purposes.
TL;DR - I couldn’t find how to access the Blueprint’s interface from C++, but you can create a C++ interface, and add it onto a Blueprint. You can then implement and call it from either place.

  1. In the Unreal Editor go to C++ classes, add a new class, in the dialog scroll all the way down and pick Unreal Interface.
  2. Open the newly created class, it’ll open in Visual Studio.
  3. You don’t need to touch the .cpp file, but in the generated .h file there will be something like
UINTERFACE(MinimalAPI)
class UHelloInterface : public UInterface
{
	GENERATED_BODY()
};

/**
 * 
 */
class MYGAME_API IHelloInterface
{
	GENERATED_BODY()

	// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
};
  1. So in there (under public of the IHelloInterface) add your function you want to call:
public:
	UFUNCTION(BlueprintCallable, BlueprintImplementableEvent, Category = "Hello")
	void Hello(int exampleParameter);
  1. Now, in the editor, if you open one of your blueprints, under Class Settings it is now possible to add this interface. And in the Functions add a function overriding the method Hello() (e.g. do a PrintScreen node there and print the number passed in)

  2. Now the fun part, calling this from C++:

		AActor* spawned = world->SpawnActor(classToSpawn, &location, &rotator, params);

		if (spawned) {
			bool isHello = spawned->GetClass()->ImplementsInterface(UHelloInterface::StaticClass());

			if (isHello) {
				IHelloInterface* hello = Cast<IHelloInterface>(spawned);
				hello->Execute_Hello(spawned, 420);
			}
		}

This contains most, but still not all the info needed to make it work: Interfaces | Unreal Engine Documentation