先创建属性组件

class ACTIONROGUELIKE_API USAttributeComponent : public UActorComponent

属性组件肯定要有数据啦

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Attributes")
float Health;

创建委托事件

//.h
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FOnHealthChanged, AActor*, InstigatorActor, USAttributeComponent*, OwningComp, float, NewHealth, float, Delta);


UFUNCTION(BlueprintCallable, Category = "Attributes")
bool ApplyHealthChange(float Delta);

UPROPERTY(BlueprintAssignable)
FOnHealthChanged OnHealthChanged;


//.cpp
bool USAttributeComponent::ApplyHealthChange(float Delta)
{
Health += Delta;
OnHealthChanged.Broadcast(nullptr, this, Health, Delta);
return true;
}

交互的开始

C++初始

给需要属性的Actor添加组件

// ACharacter or APawn
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
USAttributeComponent* AttributeComp;

void ASCharacter::PostInitializeComponents()
{
Super::PostInitializeComponents();
AttributeComp->OnHealthChanged.AddDynamic(this, &ASCharacter::OnHealthChanged);
}
void ASCharacter::OnHealthChanged(AActor* InstigatorActor, USAttributeComponent* OwningComp, float NewHealth,
float Delta)
{
if(NewHealth <= 0.f && Delta < 0.f)
{
APlayerController* PC = Cast<APlayerController>(GetController());
DisableInput(PC);
}
}

蓝图初始

在蓝图中选中需要属性的Actor,添加属性组件,选中属性组件,在属性面板中重载属性变更事件OnHealthChanged

blueprint

C++交互

ASMagicProjectile::ASMagicProjectile()
{
SphereComp->SetSphereRadius(20.0f);
SphereComp->OnComponentBeginOverlap.AddDynamic(this, &ASMagicProjectile::OnActorOverlap);

DamageAmount = 20.0f;
}

void ASMagicProjectile::OnActorOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep,
const FHitResult& SweepResult)
{
if (OtherActor && OtherActor != GetInstigator())
{
USAttributeComponent* AttributeComp = Cast<USAttributeComponent>(
OtherActor->GetComponentByClass(USAttributeComponent::StaticClass()));
if (AttributeComp)
{
AttributeComp->ApplyHealthChange(-DamageAmount); // 在需要触发属性变更的地方调用,这个使用的是魔珐弹碰撞时时触发
Explode();
}
}
}

蓝图交互

蓝图交互同C++,可绑定个按钮事件做测试。在蓝图中获取有属性的Actor,通过蓝图节点GetComponentByClass获取组件,调用对应事件即可。