Today, I spent the entire day figuring out how to translate a blueprint cast into a C++ cast. Keep in mind I’m basically a noob at C++. The simplest things take the longest when you’re new to anything.


Casting Syntax: Cast<CLASSNAME>(OBJECT TYPE)

Tweak Object Ptr Syntax (MUST be in the protected section of the header file):

TweakObjectPtr<Class CLASSNAME> VAR_NAME

Tweak Object Ptr Syntax (.cpp) 




Casts cannot be put in the constructor. It will crash Unreal Engine. 



I need to convert Blueprint Cast to C++ Cast

UCameraComponent* CameraPtr = Cast(UGameplayStatics::GetPlayerCharacter(GetWorld(),0))->FindComponentByClass();

First, we need to understand the syntax. In Unreal Engine, you could use their version of Cast or the C++ Cast. It doesn’t matter.
As so eloquently described by Alen Loeb in this video. The syntax is:
Cast(Object your casting from);

It compares to the blueprint equivalent like this:

I wanted my cast to AVrCharacter to get the camera component and save it as a UCameraComponent Reference.
If you come from blueprints you’d logically think you’d have to do this:


But that’s wrong. GetPlayerCharacter() is included in “Classes/Kismet/GameplayStatics.h” and has two parameters you need to put into it.


*Do not do* 
GetWorld()->GetPlayerCharacter(), because GetWorld() doesn’t include GetPlayerCharacter().

If you are trying to access the Player Character you need to do: UGameplayStatics::GetPlayerCharacter(GetWorld(),0) instead

The rest is easy:
Just find the right component using FindComponentByClass<>();

If you’re saving this to a reference/pointer variable, there’s a better way to do this.

You would have to use TweakObjectPtr<>

The syntax goes as follows:

TweakObjectPtr<Class> Variable

As close as I can figure, this is Variable type. As you’ll have this in your .cpp/.h:

TWeakObjectPtr<UCameraComponent> Camera

Why is this so useful?

It allows you to do this: “Camera->”!

You can set his variable type to a cast, as I did. 

You can put this into your header file for convenience. 

In your UCLASS, under the “protected:” use the following syntax to create the member variable.


In example, 

TWeakObjectPtr<class UCameraComponent> Camera; 

TWeakObjectPtr Camera = Cast(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0))->FindComponentByClass();Distance = (Camera->GetComponentLocation() - LastPosition).Size() + Distance; LastPosition = Camera->GetComponentLocation()