首页 > 解决方案 > Unreal GAS:当属性改变时将其当前值打印到 UI

问题描述

当属性的基值发生变化时,UAttributeSet::PostGameplayEffectExecute()可以访问(新)值和GameplayEffect及其上下文。我正在使用它来将更改的值打印到 UI(这也在 ActionRPG 中完成)。

属性的当前值是否有类似的可用值?如何通知 UI,何时FGameplayAttributeData::CurrentValue更新?


标签: c++unreal-engine4unreal-gameplay-ability-system

解决方案


GameplayAbilitySystem 具有UAbilitySystemComponent::GetGameplayAttributeValueChangeDelegate()返回类型的回调,该回调FOnGameplayAttributeValueChange在属性更改时触发(基值或当前值)。这可用于注册委托/回调,可用于更新 UI。

最小的例子

MyCharacter.h

// Declare the type for the UI callback.
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FAttributeChange, float, AttributeValue);

UCLASS()
class MYPROJECT_API MyCharacter : public ACharacter, public IAbilitySystemInterface
{
    // ...

    // This callback can be used by the UI.
    UPROPERTY(BlueprintAssignable, Category = "Attribute callbacks")
    FAttributeChange OnManaChange;

    // The callback to be registered within AbilitySystem.
    void OnManaUpdated(const FOnAttributeChangeData& Data);

    // Within here, the callback is registered.
    void BeginPlay() override;

    // ...
}

MyCharacter.cpp

void MyCharacter::OnManaUpdated(const FOnAttributeChangeData& Data)
{
    // Fire the callback. Data contains more than NewValue, in case it is needed.
    OnManaChange.Broadcast(Data.NewValue);
}

void MyCharacter::BeginPlay()
{
    Super::BeginPlay();
    if (AbilitySystemComponent)
    {
        AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(MyAttributeSet::GetManaAttribute()).AddUObject(this, &MyCharacterBase::OnManaUpdated);
    }
}

MyAttributeSet.h

UCLASS()
class MYPROJECT_API MyAttributeSet : public UAttributeSet
{
    // ...
    UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing=OnRep_Mana)
    FGameplayAttributeData Mana;

    // Add GetManaAttribute().
    GAMEPLAYATTRIBUTE_PROPERTY_GETTER(URPGAttributeSet, Mana)

    // ...
}

通过角色蓝图的 EventGraph 更新 UI 的示例,源自MyCharacter. UpdatedManaInUI是将值打印到 UI 的函数。

更新蓝图中的属性

在这里,UpdatedManaInUI自己检索值。您可能想使用AttributeValueof OnManaChange


推荐阅读