I am trying to make a component in c++ and i want anything that has this components attached to change color when clicked on with left mouse button, the function isn’t called whenever i click on the actor to which this component is attached, i have made sure that the player controller has On click events enabled
Here is the code for header file:
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "ClickableComponent.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent))
class ISLECRAFTERS_API UClickableComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UClickableComponent();
protected:
// Called when the game starts
virtual void BeginPlay() override;
private:
UFUNCTION(BlueprintCallable, Category = "OnClick")
void Clicked(AActor* ClickedActor, FKey KeyPressed);
class UStaticMeshComponent* Mesh;
bool IsClicked = false;
UPROPERTY(EditAnywhere, Category = "Material")
UMaterialInterface* ClickedMaterial;
UPROPERTY(EditAnywhere, Category = "Material")
UMaterialInterface* SpawnedMaterial;
};
and here is the cpp file:
// Fill out your copyright notice in the Description page of Project Settings.
#include "ClickableComponent.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/PlayerController.h"
#include "Kismet/GameplayStatics.h"
// Sets default values for this component's properties
UClickableComponent::UClickableComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UClickableComponent::BeginPlay()
{
Super::BeginPlay();
Mesh = GetOwner()->FindComponentByClass<UStaticMeshComponent>();
GetOwner()->OnClicked.AddDynamic(this, &UClickableComponent::Clicked);
}
void UClickableComponent::Clicked(AActor* ClickedActor, FKey KeyPressed)
{
UE_LOG(LogTemp, Warning, TEXT("Clicked"));
IsClicked = !IsClicked;
if(IsClicked)
{
UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(ClickedMaterial, Mesh);
Mesh->SetMaterial(0, DynamicMaterial);
}
else
{
UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(SpawnedMaterial, Mesh);
Mesh->SetMaterial(0, DynamicMaterial);
}
}
the custom clicked function that i have created doesn’t get called, i think the problem is with binding and i am not able to fix it, I tried making the function blueprintcallable and then binding it from the blueprint event graph, then it seems to work fine but i wanna do it entirely in c++ for some future reasons.