Can someone explain me how to create the component and attach to the root component of my actor?
Try :
RootComponent = SpellCaster;
I thought you knew, according to your screenshot, since it is the correct way to create your component. Then, to initialize, you just have to set any property from here :
SpellCaster->SpellArray.Add(whatEver));
Or set the values directly in the constructor of your UActorComponent.
About the RootComponent, I did not see that it was an UActorComponent and not an USceneComponent. And as you said in your previous comment, only USceneComponents can be attached. So, you should inherit from USceneComponent instead of UActorComponent.
I have found that only USceneComponents are supposed to be attached with “AttachTo” method. However, I still cannot find a way to add ActorComponents to Actors.
This does not help me in two things. First I still do not know how to initialize a component in c++. Second, my RootComponent holds USceneComponents.
I believe I have solved the problem. There are things to mention before the solution:
“AttachTo” method is belong to "USceneComponent"s. Therefore, you are not supposed to attach an “ActorComponent” to them. The idea of attaching a component which is not a “USceneComponent” is also not true. If your component does not have any attribute in 3d world, you are not supposed to attach it to the components having attributes in 3d world.
Solution:
-
It is correct to create a component by using
"CreateDefaultSubobject(TEXT("YourComponentName"))
. -
If you dive into the API document for [AActor][1], you find a method [
AddOwnedComponent( UActorComponent * Component
)][2]. Yes, this is the method you should call if you want to add an actor component into your actor.
Here is my SpellCaster component inside a blueprint of my “Hero” class:
How would this work if you wanted to parameterize the template for which actor component is created? I intend to have a class defined in a variable in blueprint that gets passed to this function.
UActorComponent* UApolloLibrary::ConstructActorComponent(UClass *actorComponent, class AActor *owner, FText name)
{
UActorComponent *newComp = owner->CreateDefaultSubobject<actorComponent>(name);
owner->AddOwnedComponent(newComp);
return newComp;
}
This currently doesn’t compile as I’m still trying to figure it out. How to Dynamically Instantiate Actor Components? - Blueprint - Epic Developer Community Forums
This helped me figure it out, thanks!