Blueprint is a wonderful tool, letting you visually assemble code. However there is a point at which its beauty turns into spaghetti, and you’re better-off coding the behaviour in the more powerful and more flexible C++ environment. Here I briefly show how you can call a C++ function from a Blueprint in Unreal Engine.
You start off by using the UFUNCTION macro directly above the declaration of the function you want to call from Blueprint, as seen below. In this case the type we are taking in is UChildActorComponent*, a pointer to a child actor component type. We call this variableTurretFromBP.
Picture

Once you have compiled your code, head over into blueprint. Find something of the same type that you specified in the code, in my case the turret of my tank is a child actor for flexibly. We drag a pin from Tank Turret BT, and in the menu that pops-up there will now be a function called “SetTurretChildActor”.

Remember to trigger this set event by using the white execution lines, in this case I’m setting the reference on BeginPlay.

Picture

So now the reference to the asset has been “soft coded” as opposed to “hard coded”. This means we can rename parts Blueprint without losing track, and swap-out assets. Furthermore this is a reliable way of keeping the code connected to the right part, without imposing any weird restrictions on the Hierarchy like “the turret should always be the first child”.

Now back over in C++ we can write a very simple setter method to set a local variable, and we have the reference we need to do rotations, and whatever else we like with the component.

Picture

This is a really quick blog post I’ve written as part of the production of the Unreal Course.