Sergey  Pekar
Sergey Pekar

Reputation: 8745

Bind user input to UActorComponent methods in UE4.22.3 and Up

I am trying to create UActorComponent which will handle some user input. I am doing it this way:

void MyComponent::BeginPlay()
{
    Super::BeginPlay();
    this->InputComponent = GetOwner() ->FindComponentByClass<UInputComponent>();

    if (this->InputComponent != nullptr) {
        UE_LOG(LogTemp, Display, TEXT("%s InputComponent Found"), *(GetReadableName()));

        this->InputComponent->BindAction("MyAction", IE_Pressed, this, &MyComponent::ActionStart);
        this->InputComponent->BindAction("MyAction", IE_Released, this, &MyComponent:: ActionEnd);

        UE_LOG(LogTemp, Display, TEXT("%s InputComponent Binding done"), *(GetReadableName()));
    }
}

However component's methods never called. I found out that all the bindings gone after Pawns SetupPlayerInputComponent method is called. If I do all bindings inside SetupPlayerInputComponent all the bindings work properly.

So what is a best way to handle user input inside UActorComponent or it is not good practice at all?

Upvotes: 2

Views: 3191

Answers (2)

Josip Duvancic
Josip Duvancic

Reputation: 11

Inside the SetupPlayerInputComponent

InputComponent->BindAction("MyAction", IE_Pressed, MyComponentRef, &MyComponent::ActionStart);

As for it being good practice or not, it can have its perks, mainly to reduce clutter or reuse the Input Handlers across several unrelated subclasses of APawn.

Upvotes: 1

Playdome.io
Playdome.io

Reputation: 3225

As you mentioned the bindings work if you call the functions inside SetupPlayerInputComponent so the easiest solution would be is to create a function in your component called SetupInput and call that function from your pawn's SetupPlayerInputComponent function.

And yes in my opinion bindings should be handled by either the controlled pawn or the player controller as thats how the ue4 game framework works. I'd move all my inputs inside the controller if you don't have any specific pawn to control or if it's just a camera move it inside a Pawn itself.

Upvotes: 1

Related Questions