Announcement

Collapse
No announcement yet.

How to add an ActorComponent dynamically?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to add an ActorComponent dynamically?

    I'm making a system where I add different components to a building depending on the values I pass to it. I can't figure out how to add these components and get them back when I need to reference them.

    #2
    You could write a function that takes a pointer to the AActor you want to attach to, a UClass pointer for the component class you want attached to the actor, and an FString for the name you want to name the component. Something like:

    Code:
    UActorComponent* AttachComponentToActor(AActor* TheActor, UClass* TheComponent, const FString& ComponentName);
    When you pass the component class to this function, it'll be something like this:
    Code:
    UClassOfComponentYouWantToAttach::StaticClass()
    Now, inside of this function, to make the component:

    Code:
    UActorComponent* NewComponent = NewObject<UActorComponent>(TheActor, TheComponent, FName(*ComponentName));
    Then you can attach it to the actor, and return it as a UActorComponent* so you have a reference to it you can use later.
    Last edited by Ed.Kaminski; 05-12-2020, 11:12 AM.

    Comment


      #3
      One more thing, if you want some idea of how you can attach it to the actor after creation, checkout SSCEditor::AddNewComponent from SSCEditor.cpp -- you can do some similar code to what this function does.

      Comment


        #4
        You should not use the Blueprint functionality for creating an Actor Component at runtime. The correct way to create one is this:

        Code:
        UActorComponent* NewComponent = NewObject<UActorComponent>(TheActor, ComponentClass, NAME_None, RF_Transient);
        check(NewComponent);
        
        NewComponent->RegisterComponent();
        If you do not register the component properly, numerous features will not work correctly.

        Comment

        Working...
        X