Download

Casting Help with TSubobjectPtr




AVRShooterCharacter::AVRShooterCharacter(const class FPostConstructInitializeProperties& PCIP)
: Super(PCIP.SetDefaultSubobjectClass<UVRCharacterMovementComponent>(ACharacter::CharacterMovementComponentName))
{
	if ((TSubobjectPtr<class UVRCharacterMovementComponent>)CharacterMovement != NULL)
	{
		VRMoveComp = (TSubobjectPtr<class UVRCharacterMovementComponent>)CharacterMovement;
	}
}



Basically, I am trying to use a cast so I can call the custom functions in the movement component I wrote, however, it is not working.
“cannot access private member declared in class 'TSubobjectPtr<UVRCharacterMovementComponent>”

Any help is much appreciated.

Since that is your goal try doing this instead


UVictoryCharMoveComp* CustomCharMovementComp = Cast<UVictoryCharMoveComp>(CharacterMovement);
 
if(CustomCharMovementComp)
{
  CustomCharMovementComp->CallFunction();
}

I have updated my wiki tutorial here:

Rama

Thanks! That accomplishes what I needed.

A couple of things I’d like to add; you should always avoid C style casts where possible, especially when you’re trying to downcast.


if ((TSubobjectPtr<class UVRCharacterMovementComponent>)CharacterMovement != NULL)

What you’re doing there isn’t checking whether *CharacterMovement *points to an object of type UVRCharacterMovementComponent, you’re just telling the compiler to always treat it like it is one, and the *!= NULL *part will return true even if *CharacterMovement *isn’t a UVRCharacterMovementComponent. This is where the Unreal Engine function Cast<> comes in. It uses the *UClass *system to check at runtime whether the object can actually be cast to that type safely, if not it returns NULL. Note that *Cast<> *only works on classes that inherit from UObject, to cast other types, use C++ style casts like static_cast<>.