Puerts项目:在TypeScript中调用Unreal C++类的完整指南
前言
在Unreal Engine游戏开发中,Puerts项目为开发者提供了在TypeScript中直接调用C++类的能力,极大地提升了开发效率和灵活性。本文将全面介绍如何在TypeScript中与Unreal C++类进行交互,包括反射API和非反射API的使用方法。
反射API的调用
反射API是指那些在Unreal Engine中被标记为UCLASS
、UPROPERTY
、UFUNCTION
、USTRUCT
或UENUM
的C++类和成员。这些API可以直接在TypeScript中使用,无需额外配置。
基本使用示例
C++端代码
UCLASS()
class UDemoGameInstance : public UGameInstance
{
GENERATED_BODY()
public:
UFUNCTION()
void PrintExampleVariable()
{
UE_LOG(LogTemp, Warning, TEXT("%s"), *ExampleVariable);
}
protected:
UPROPERTY()
FString ExampleVariable{};
};
TypeScript端调用
const DemoGameInstance = argv.getByName("GameInstance") as UE.DemoGameInstance;
DemoGameInstance.ExampleVariable = "Hello World!";
DemoGameInstance.PrintExampleVariable(); // 控制台输出"Hello World!"
容器类型的使用
Puerts支持Unreal Engine中的各种容器类型,包括TArray、TSet和TMap:
// 创建不同类型的数组
const IntArray = UE.NewArray(UE.BuiltinInt);
const StringArray = UE.NewArray(UE.BuiltinString);
const ActorArray = UE.NewArray(UE.Actor);
// 创建集合和映射
const StringSet = UE.NewSet(UE.BuiltinString);
const StringIntMap = UE.NewMap(UE.BuiltinString, UE.BuiltinInt);
ArrayBuffer处理
Puerts支持在TypeScript和C++之间传递二进制数据:
C++端接收ArrayBuffer
void UMyObject::ArrayBufferTest(const FArrayBuffer& InArrayBuffer) const
{
UE_LOG(LogTemp, Warning, TEXT("Buffer length = %i"), Ab.Length);
}
TypeScript端发送数据
const buffer = new Uint8Array([21, 31]);
MyUObj.ArrayBufferTest(buffer);
混合类(Mixin)功能
Puerts的混合类功能允许开发者用TypeScript扩展C++类的功能:
class MyCharacter extends UE.Character {
// 可以重写C++方法或添加新方法
Tick(deltaTime: number) {
// 自定义逻辑
}
}
非反射API的调用
对于没有反射标记的C++类和函数,Puerts提供了模板绑定机制来暴露这些API。
模板绑定示例
C++端绑定
// 绑定非反射类
class UnreflectedClass {
public:
void TestMethod();
};
// 使用模板绑定
UsingCppType(UnreflectedClass);
TypeScript端调用
const instance = new UE.UnreflectedClass();
instance.TestMethod();
最佳实践
- 优先使用反射API:反射API使用简单,维护成本低
- 合理使用混合类:对于需要频繁修改的逻辑,考虑使用混合类
- 性能敏感操作放在C++端:复杂计算或性能敏感操作建议保留在C++中
- 注意内存管理:了解Unreal Engine的对象生命周期管理机制
常见问题
Q: 为什么我的C++类在TypeScript中不可见? A: 确保类已正确添加反射标记,并重新生成项目文件
Q: 如何调试TypeScript调用C++的过程? A: 可以使用UE_LOG输出调试信息,或使用Puerts提供的调试工具
Q: 性能开销如何? A: 反射API调用有少量开销,对于高频调用应考虑优化方案
通过Puerts项目,开发者可以充分利用TypeScript的灵活性和C++的性能优势,为Unreal Engine项目开发带来全新的可能性。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考