Is this correct way of using interface in CPP? (Collecting PickUps)

Hi. I created Interface and Coin that implements it. But I feel like Im doing something wrong. Because I use interface. Then In this coin I cast value that I passed (Acharacter) and set variables inside of my character. Maybe I should just use OnOverlapEvent Cast to this character and just set value. I just made interface if there would be something else than coins for example heart (for healing). Heres my code:


// character
void APlatformer3dCharacter::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
	UPrimitiveComponent* Component, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	
	 if(IICollectItem* Interface = Cast<IICollectItem>(OtherActor))
	 {
		Interface->OnPickUpItem_Implementation(this);
	 }

	 
}
// coin

 
	void AACoin::OnPickUpItem_Implementation(ACharacter* PlayerCharacter)
	{
			 
		if (PlayerCharacter)
		{
			UE_LOG(LogTemp, Warning, TEXT("OnPickUpItem for character: %s"), *PlayerCharacter->GetClass()->GetName());

			// Attempt to cast PlayerCharacter to APlatformer3dCharacter
			if (APlatformer3dCharacter* Character = Cast<APlatformer3dCharacter>(PlayerCharacter))
			{
				// Update the Coins variable
				Character->Coins += 10;
				 
			}
interface

	UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category= CollectItem)
	void OnPickUpItem(ACharacter* PlayerCharacter);
	

it really just depends on your game, interfaces are more for modularity,

ie you may have many different items that the player can pick up so it makes sense to use an interface, however you may only have one player character in which case its fine to cast.

if you wanted multiple character types then you could use another interface back to set any variables.

other options are to add a return on your interface and the player updates itself or just pass through that player as an input and then there is no need to cast.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.