TSubclassOf

Windows
MacOS
Linux

TSubclassOf 是提供 UClass 类型安全性的模板类。例如您在创建一个投射物类,允许设计者指定伤害类型。您可只创建一个 UClass 类型的 UPROPERTY,让设计者指定派生自 UDamageType 的类;或者您可使用 TSubclassOf 模板强制要求此选择。以下示例代码展示了不同之处:

/** type of damage */
UPROPERTY(EditDefaultsOnly, Category=Damage)
UClass* DamageType;

Vs.

/** type of damage */
UPROPERTY(EditDefaultsOnly, Category=Damage)
TSubclassOf<UDamageType> DamageType;

在第二个声明中,模板类告知编辑器的属性窗口只列出派生自 UDamageType 的类(作为属性选择)。在第一个声明中可选择任意 UClass。下图对此进行了说明。

image alt text

策略游戏投射物蓝图的范例

除 UPROPERTY 安全外,您还能获得 C++ 层级上的类型安全。如尝试进行不兼容 TSubclassOf 类型的相互指定,将出现编译错误。尝试指定泛型 UClass 时,它将执行一个运行时检查,以确定它可执行指定。如运行时检查失败,结果数值为 nullptr。

UClass* ClassA = UDamageType::StaticClass();

TSubclassOf<UDamageType> ClassB;

ClassB = ClassA; // Performs a runtime check

TSubclassOf<UDamageType_Lava> ClassC;

ClassB = ClassC; // Performs a compile time check
Select Skin
Light
Dark

Welcome to the new Unreal Engine 4 Documentation site!

We're working on lots of new features including a feedback system so you can tell us how we are doing. It's not quite ready for use in the wild yet, so head over to the Documentation Feedback forum to tell us about this page or call out any issues you are encountering in the meantime.

We'll be sure to let you know when the new system is up and running.

Post Feedback