Search code examples
c++game-developmentunreal-engine4unreal-engine5

How to attach scene component to actor from the c++ code in Unreal Engine 5


I need to attach a scene component to an actor but in a way that i will be able to access the things(function, variables) in the scene component from another actor. for example, i have an actor called Door1 and i have a scene component called DoorSceneComponent and i want to attach the DoorSceneComponent to the root of Door1 but in the c++ code, not in the Unreal Editor. I also have a Character class called PlayerCharacter in this class, i have a refrence to Door1, the thing is that i want to be able to call a function that is defiened in DoorSceneComponent from the PlayerCharacter class. My question is, how can i attach the DoorSceneComponent to Door1 in c++? I use Unreal Engine 5.1 I use Manjaro Linux as my OS. If you need any more information just say. Thanks :)


Solution

  • This one takes a couple separate parts. Firstly, you'll want to hold a pointer to an instance of your DoorSceneComponent. So in your Door1 header:

    Door1.h

    private: //(or protected, depending on your needs)
    UPROPERTY()
    DoorSceneComponent* DoorComp;
    

    (If it has properties that need to be edited in the editor, then you'll need to add one of these tags to the UPROPERTY depending on what exact behaviour you require.)

    In your Door1 constructor, you need to actually create the scene component:

    Door1.cpp

    ADoor1::ADoor1() {
        // Create the component
        DoorComp = CreateDefaultSubobject<UDoorSceneComponent>(TEXT("Door Component));
        // Attach it to the root
        DoorComp->SetupAttachment(RootComponent);
    }
    

    CreateDefaultSubobject

    SetupAttachment

    Once you've done this and recompiled, the component will be attached in any blueprints/instances of your actor.