UE C++ 组件 非构造函数创建的技巧

如果是构造函数,相信大家都会,如果不是构造函数,核心就是NewObject。

  1. 在运行时构建

这里构建Ceiusm的一个组件

复制代码
		globeAnchor = NewObject<UCesiumGlobeAnchorComponent>(Cast<UObject>(this),UCesiumGlobeAnchorComponent::StaticClass(),TEXT("GlobeAnchor"),RF_Transactional);         // 支持Undo/Redo
		//AddOwnedComponent(globeAnchor);
		//globeAnchor->AttachToComponent(RootComponent,FAttachmentTransformRules::KeepRelativeTransform);
		globeAnchor->RegisterComponent();
		AddInstanceComponent(globeAnchor);

UClass* baseClass = FindObject<UClass>(ANY_PACKAGE, TEXT("CameraComponent"));
UCameraComponent* tmpComp = NewObject<UCameraComponent>(Cast<UObject>(this), baseClass, *it.CameraName);
tmpComp->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
tmpComp->RegisterComponent();
AddInstanceComponent(tmpComp);

FRotator camRot = it.CameraRot;
//添加通道偏移
camRot += FRotator(m_channelData.offsetPatch, m_channelData.offsetYaw, m_channelData.offsetRoll);

tmpComp->SetRelativeLocation(it.CameraPos);
tmpComp->SetRelativeRotation(camRot);

其实核心就是 NewObject,RegisterComponent,AddInstanceComponent。

1. NewObject

  • 用于动态创建一个UObject派生类的实例。

  • 参数包括Outer(用于内存管理)、类名、对象名、标志等。

  • 这里创建了一个UCesiumGlobeAnchorComponent实例。

2. RegisterComponent

  • 将组件注册到引擎中,使其成为激活状态,参与游戏逻辑。

  • 注册后,组件会收到BeginPlay等事件,并每帧更新(如果需要)。

3. AddInstanceComponent

  • 将组件添加到Actor的实例组件列表中,并自动注册组件(如果尚未注册)。

  • 同时设置组件的外部对象(Outer)为当前Actor,并管理组件的生命周期。

二.NewObject 标志位的思考

我在场景里删了globeranchor,又把它组装上结果我在运行时编译器里没看到。如果在编辑器,添加,或者构造函数里添加都能在编辑器里看到经纬度参数的变化,但删除后,再用NewObject,居然就看不到了,可是断点里明明生成成功了。于是使用了RF_Transactional。

如果实例化的组件,总哪里不对,说不定是参数不对。这里应该是属于重做了这个组件,也不确定,留作日后思考。

  1. RF_Public:对象在其包外可见。通常用于需要在蓝图中或其它类中访问的对象。

  2. RF_Standalone:即使没有被引用,也保留对象以供编辑。这通常用于在编辑器中独立存在的对象,比如一个放在关卡中的Actor。

  3. RF_MarkAsNative:在构造时标记为原生(仅用于UField及其派生类)。不要在其他地方使用这个标志进行检测。

  4. RF_Transactional:对象是事务性的,支持撤销/重做。常用于编辑器中的对象。

  5. RF_ClassDefaultObject:此对象是其类的默认对象(即类默认对象,CDO)。

  6. RF_ArchetypeObject:此对象是另一个对象的模板(类似于类默认对象,但用于实例的模板)。

  7. RF_Transient:不保存对象。通常用于运行时临时对象,不会保存到磁盘。

三.删除

复制代码
		globeAnchor->DestroyComponent();
		globeAnchor = nullptr;
相关推荐
AC赳赳老秦35 分钟前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
提笔了无痕37 分钟前
如何用Go实现整套RAG流程
开发语言·后端·golang
(Charon)39 分钟前
【C++ 面试高频基础:指针、引用、const、static、new/delete 总结】
java·开发语言
2601_961875241 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
AI科技星1 小时前
数术工坊第八卷:算力革命
c语言·开发语言·网络·量子计算·agi
Frank学习路上1 小时前
【C++】面试:关键字与语法特性
c++·面试
geovindu2 小时前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式
Irissgwe2 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
码云骑士3 小时前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python
点云侠3 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法