UE5 动态创建Component

在UnrealEngine中,创建Component后,使用SetupAttachment而非AttachToComponent主要是因为前者可以在Component未注册时使用。SetupAttachment用于初始化附加的父组件和插座名,而AttachToComponent要求Component已经注册。选择哪个方法取决于Component的注册时机和业务需求。
摘要由CSDN通过智能技术生成

创建的过程

  • 创建一个Component的UObject
  • 将创建的Component附加到它的Parent Parent(或者Actor)上
  • 注册这个Component

代码

// 没啥好说的,创建
UXXComponent* XXCmp = NewObject<UXXComponent>(this, UXXComponent::StaticClass());
XXCmp -> SetupAttachment(this);//当前的this是一个Component
...// 一些对此XXCmp的设置
XXCmp->RegisterComponent()

问题

关于创建之后为啥使用SetupAttachment,而不是AttachToComponent,上源码

	/**
	 * Attaches the RootComponent of this Actor to the supplied component, optionally at a named socket. It is not valid to call this on components that are not Registered.
	 * @param  Parent					Parent to attach to.
	 * @param  AttachmentRules			How to handle transforms and welding when attaching.
	 * @param  SocketName				Optional socket to attach to on the parent.
	 */
	void AttachToComponent(USceneComponent* Parent, const FAttachmentTransformRules& AttachmentRules, FName SocketName = NAME_None);

说的是将这个actor的RootComponent添加到给定的Component上或者socket,并且,当component没有注册时,这个方法无效的
我们再来看一下这个代码

	/** 
	* Initializes desired Attach Parent and SocketName to be attached to when the component is registered.
	* Generally intended to be called from its Owning Actor's constructor and should be preferred over AttachToComponent when
	* a component is not registered.
	* @param  InParent				Parent to attach to.
	* @param  InSocketName			Optional socket to attach to on the parent.
	*/
	void SetupAttachment(USceneComponent* InParent, FName InSocketName = NAME_None);

简而言之,就是还没注册是,可以调用它

结论

附加的时机不同,是根据注册的时机决定的,同时看业务时机使用场景

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值