虚幻引擎4—类型转换

Unreal Engine 4 -- Typecasting

本文关键字:类型转换 引擎      更新时间:2023-10-16

我目前正在虚幻引擎4中开发我的第一个类。由于广泛使用UScript,我对纯c++中的类型转换如何工作感到有点困惑。更具体地说,是类/对象强制转换。

我目前正在MyCustomGameMode中放置一个开关语句,它调用MyCustomPlayerController的MyCustomPlayerControllerVariable。

我要重写的函数是这个:virtual UClass* GetDefaultPawnClassForController(AController* InController);

目前,我正试图用以下代码行调用变量,我知道这是不正确的,但我不确定为什么:

Cast<MyCustomPlayerController>(InController).MyCustomPlayerControllerVariable

我有兴趣将"InController"转换为MyCustomPlayerController,但Cast<MyCustomPlayerController>(InController)似乎不起作用,我在这里做错了什么?

cast将返回一个指向播放器控制器的指针,所以你需要使用->来解引用它。

const MyCustomPlayerController* MyController = Cast<MyCustomPlayerController>(InController);
check(MyCustomPlayerController);  // asserts that the cast succeeded
const float MyVariable = MyCustomPlayerController->ControllerVariable;

"

强制类型转换时,它总是返回一个指针。因此,在从指针访问变量之前,请确保检查强制转换是否成功。

auto MyPC = Cast<MyCustomPlayerController>(InController);
if(MyPC)
{
    MyPC->MyVariable;
}