How to declare a variable that it is a pointer to another actor?

Hi!

I created an interface to allow the player interact with an actor when it is close enough. This is the code for that actor.

Header:

private:
    TObjectPtr<class ILeverInteract> PlayerCharacter;

Code:

void MyClass::OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	PlayerCharacter = Cast<ILeverInteract>(OtherActor);
	
	if (PlayerCharacter)
	{
		PlayerCharacter->LeverInteractDelegate.AddUniqueDynamic(...);
	}
}

void MyClass::OnOverlapEnd(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
	if (PlayerCharacter)
	{
		PlayerCharacter->LeverInteractDelegate.RemoveDynamic(...);
	}
}

My question is: how do I have to declare the PlayerCharacter variable?

I have used TObjectPtr, but I don’t know if it is the best choice to declare it.

Thanks!

TObjectPtr is virtually equivalent to a raw pointer. So both ILevelInteract* PlayerCharacter and TObjectPtr<ILevelInteract> PlayerCharacter will do. But Epic Games suggest using TObjectPtr<>, so why not.

1 Like

You will want to put UPROPERTY() in front of your object variable.

The reason is that the Unreal garbage collector/reference system doesn’t know about properties that aren’t marked with UPROPERTY()

2 Likes