c++ - Unreal GAS:当属性改变时将其当前值打印到 UI
问题描述
当属性的基值发生变化时,UAttributeSet::PostGameplayEffectExecute()
可以访问(新)值和GameplayEffect及其上下文。我正在使用它来将更改的值打印到 UI(这也在 ActionRPG 中完成)。
属性的当前值是否有类似的可用值?如何通知 UI,何时FGameplayAttributeData::CurrentValue
更新?
- 尽管
UAttributeSet::PreAttributeChange()
在每次值更新时都会调用它,但它不提供任何上下文,因此无法从那里访问 UI(由广播的事件FAggregator
也不适合)。 - 可以改用GameplayCue来设置
FGameplayAttributeData::CurrentValue
UI 中的值(提示由设置当前值的GameplayEffect触发)。这可以通过从 a 派生GameplayCueNotifyActor
并使用它的事件OnExecute
和来实现OnRemove
。然而,仅仅为了更新 UI 而实例化一个 Actor 似乎是一种资源浪费。 - 也可以使用 UI 本身来获取信息(调用一个函数来访问每个刻度或使用计时器),但与事件驱动的 UI 更新相比,这也是一种浪费。
解决方案
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
自己检索值。您可能想使用AttributeValue
of OnManaChange
。