【虚幻引擎属性绑定UI实现方案】该代码展示了在虚幻引擎中通过GameplayAbilitySystem(GAS)将游戏属性动态绑定到UI控件的方法。核心实现包括:
1) 在ValueGauge类中创建SetAndBoundToGameplayAttribute函数,通过GetGameplayAttributeValue获取属性初始值,并使用GetGameplayAttributeValueChangeDelegate注册属性变化回调;
2) 在GameplayWidget的NativePreConstruct中调用该函数,将生命条/法力条与对应属性绑定;
3) 属性变化时自动更新UI显示,包含百分比计算和颜色变化逻辑(如低血量变红)。该方案实现了属性系统与UI的自动同步,是GAS框架下常用的UI交互模式。
1.设置和绑定到游戏属性:
Source/Crunch/Public/UI/Widget/ValueGauge.h:
添加函数:
//设置和绑定到游戏属性
void SetAndBoundToGameplayAttribute(UAbilitySystemComponent* AbilitySystemComponent,
const FGameplayAttribute& Attribute,const FGameplayAttribute& MaxAttribute);
void UValueGauge::SetAndBoundToGameplayAttribute(UAbilitySystemComponent* AbilitySystemComponent,
const FGameplayAttribute& Attribute, const FGameplayAttribute& MaxAttribute)
{
if(AbilitySystemComponent)
{
bool bGetAttribute;
bool bGetMaxAttribute;
float Value = AbilitySystemComponent->GetGameplayAttributeValue(Attribute,bGetAttribute);
float MaxValue = AbilitySystemComponent->GetGameplayAttributeValue(MaxAttribute,bGetMaxAttribute);
if (bGetAttribute && bGetMaxAttribute)
{
SetValue(Value,MaxValue);
}
//订阅属性的变化: 当指定游戏属性(Attribute)发生变化时,自动调用UValueGauge类的ValueChanged方法
AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(Attribute).AddUObject(this, &UValueGauge::ValueChanged);
AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(MaxAttribute).AddUObject(this, &UValueGauge::MaxValueChanged);
}
}
其中,
(1)
float Value = AbilitySystemComponent->GetGameplayAttributeValue(Attribute,bGetAttribute);
/**
* Returns the current value of the given gameplay attribute, or zero if the attribute is not found.
* NOTE: This doesn't take predicted gameplay effect modifiers into consideration, so the value may not be accurate on clients at all times.
*
* @param Attribute The gameplay attribute to query
* @param bFound Set to true if the attribute exists in this component
*/
UFUNCTION(BlueprintPure, Category = "Gameplay Attributes")
float GetGameplay

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



