虚幻引擎UE5专用服务器游戏开发-16 更新游戏界面中的生命值与魔法值

【虚幻引擎属性绑定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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值