创建的过程
- 创建一个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);
简而言之,就是还没注册是,可以调用它
结论
附加的时机不同,是根据注册的时机决定的,同时看业务时机使用场景