Puerts项目:在TypeScript中调用Unreal C++类的完整指南

Puerts项目:在TypeScript中调用Unreal C++类的完整指南

puerts PUER(普洱) Typescript. Let's write your game in UE or Unity with TypeScript. puerts 项目地址: https://gitcode.com/gh_mirrors/pu/puerts

前言

在Unreal Engine游戏开发中,Puerts项目为开发者提供了在TypeScript中直接调用C++类的能力,极大地提升了开发效率和灵活性。本文将全面介绍如何在TypeScript中与Unreal C++类进行交互,包括反射API和非反射API的使用方法。

反射API的调用

反射API是指那些在Unreal Engine中被标记为UCLASSUPROPERTYUFUNCTIONUSTRUCTUENUM的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();

最佳实践

  1. 优先使用反射API:反射API使用简单,维护成本低
  2. 合理使用混合类:对于需要频繁修改的逻辑,考虑使用混合类
  3. 性能敏感操作放在C++端:复杂计算或性能敏感操作建议保留在C++中
  4. 注意内存管理:了解Unreal Engine的对象生命周期管理机制

常见问题

Q: 为什么我的C++类在TypeScript中不可见? A: 确保类已正确添加反射标记,并重新生成项目文件

Q: 如何调试TypeScript调用C++的过程? A: 可以使用UE_LOG输出调试信息,或使用Puerts提供的调试工具

Q: 性能开销如何? A: 反射API调用有少量开销,对于高频调用应考虑优化方案

通过Puerts项目,开发者可以充分利用TypeScript的灵活性和C++的性能优势,为Unreal Engine项目开发带来全新的可能性。

puerts PUER(普洱) Typescript. Let's write your game in UE or Unity with TypeScript. puerts 项目地址: https://gitcode.com/gh_mirrors/pu/puerts

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翟培任Lame

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值