Unreal的GAS技能系统是针对游戏技能管理的一套逻辑封装方案,这套方案考虑面较广,包括了Cooldowns技能冷却、允许多技能同时释放、GameplayTags的使用、特殊的事件触发等,今天就来学习一下。
1.激活插件与C++部分配置
1.1 创建测试工程,选择第三人称案例,C++工程。以便自动创建对应的sln文件。
1.2 以UE5.2版本进行演示,首先在插件管理器中激活GameplayAbilities插件:
1.3 打开C++工程的build.cs文件,添加GameplayAbilities模块依赖:
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class MyProject : ModuleRules
{
public MyProject(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] {
"Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "EnhancedInput", "GameplayAbilities" });
}
}
1.4 找到Character默认角色类的.h头文件,添加相关模块include并实现IAbilitySystemInterface接口:
//头文件
#include "AbilitySystemInterface.h"
#include "AbilitySystemComponent.h"
#include "Abilities/GameplayAbility.h"
//
//省略
//实现接口:
UCLASS(config=Game)
class AMyProjectCharacter : public ACharacter, public IAbilitySystemInterface
{
GENERATED_BODY()
//省略
1.5 在Character默认角色类的.h头文件中,定义几个关键函数:
public:
AMyProjectCharacter();
//该字段为IAbilitySystemInterface接口暴露字段:
UAbilitySystemComponent* GetAbilitySystemComponent()const override;
//实现技能的蓝图必须挂载该组件:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Abilities")
class UAbilitySystemComponent* AbilitySystemComponent;
//学习技能函数需要手动实现:
UFUNCTION(BlueprintCallable, Category = "Abilities")
void AquireAbility(TSubclassOf<UGameplayAbility>AbilityToAquire);
1.6 来到Character默认角色类的.cpp文件中,实现这几个函数:
AMyProjectCharacter::AMyProjectCharacter()
{
//省略
//构造函数中创建这个组件:
AbilitySystemComponent = CreateDefaultSubobject<UAbilitySystemComponent>(TEXT("AbilitySystem"));
}
//省略
//实现GetAbilitySystemComponent,返回字段即可
UAbilitySystemComponent* AMyProject2Character::GetAbilitySystemComponent() const
{
return AbilitySystemComponent;
}
//自行实现AquireAbility逻辑,其实就是调用内部的GiveAbility接口再初始化
void AMyProject2Character::AquireAbility(TSubclassOf<UGameplayAbility> AbilityToAquire)
{
if (AbilitySystemComponent) {
if (HasAuthority() && AbilityToAquire) {
AbilitySystemComponent->GiveAbility(FGameplayAbilitySpec(AbilityToAquire, 1, 0));
}
AbilitySystemComponent->InitAbilityActorInfo(this, this);
}
}
目前C++部分需要的工作已经处理完成。