How to add OnClicked event for StaticMeshComponent in ure4.7?

Hey, I tried to click StaticMeshComponent at runtime, but could not click on a specific StaticMeshComponent. I tried the following logic to click and set stuff inside the OnClick () function, but failed. Is the AddDynamic approach applied correctly?
In .cpp

    StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponentCOMP"));
    ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMesh_obj(TEXT("/Game/StarterContent/Meshs/Chairs_Chair1"));
    StaticMeshComponent->SetStaticMesh(StaticMesh_obj.Object);
    StaticMeshComponent->OnClicked.AddDynamic(this, &AMyActor::OnClick);
    StaticMeshComponent->AttachTo(RootComponent);

// OnClick Function


 void AMyActor::OnClick(UPrimitiveComponent* pComponent)
     {
ConstructorHelpers::FObjectFinder<UMaterial> MeshMaterial(TEXT("/Game/GTFreeMaterials/Materials/Metal_BrushedSteel"));

        // Set properties for Staic mesh component
        StaticMeshComponentArray[i]->SetMaterial(0, MeshMaterial.Object);
         FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Clicked")));
     }

In .h

 void OnClick(UPrimitiveComponent* pComponent);

Could you guys help me in this matter? Or advise me any other effective logic to solve my problem.

PS: Game mode: mouse click mode

+4
source share
1 answer

I just put together a quick test and everything worked correctly. Perhaps the steps I used will help you:

1, UE4.18; ++ Basic Code, Desktop/Console, Maximum Quality No Starter Content.

2, ++ Player , .

3, Game ++, , , Player Controller

4, , ++ ( → → GameMode)

5, Pawn ++ ,

6, , ++ Pawn, Cube (Static Mesh Component) , " " .

7,

8, , " ", ,

:

AMyCharacter

OnClicked.AddUniqueDynamic(this, &AMyCharacter::OnSelected);

AMyCharacter.h

UFUNCTION()
        void OnSelected(AActor* Target, FKey ButtonPressed);

AMyCharacter.cpp

void AMyCharacter ::OnSelected(AActor* Target, FKey ButtonPressed)
{
    GEngine->AddOnScreenDebugMessage(-1, 2.f, FColor::Cyan, FString("EEEEEEEEEEEEEEEEE"));
}
0

Source: https://habr.com/ru/post/1584435/


All Articles