不为人知的UE技巧
使用宏自动生成Get&Set函数
GAS的Attribute使用了这一技巧,直接使用宏添加到头文件,在定义Atribute时使用宏,就可以生成静态的Get&Set函数。
// Uses macros from AttributeSet.h
#define ATTRIBUTE_ACCESSORS(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_GETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_SETTER(PropertyName) \
GAMEPLAYATTRIBUTE_VALUE_INITTER(PropertyName)
#define GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \
static FGameplayAttribute Get##PropertyName##Attribute() \
{ \
static FProperty* Prop = FindFieldChecked<FProperty>(ClassName::StaticClass(), GET_MEMBER_NAME_CHECKED(ClassName, PropertyName)); \
return Prop; \
}
public:
UGSAmmoAttributeSet();
UPROPERTY(BlueprintReadOnly, Category = "Ammo", ReplicatedUsing = OnRep_RifleReserveAmmo)
FGameplayAttributeData RifleReserveAmmo;
ATTRIBUTE_ACCESSORS(UGSAmmoAttributeSet, RifleReserveAmmo)
UPROPERTY(BlueprintReadOnly, Category = "Ammo", ReplicatedUsing = OnRep_MaxRifleReserveAmmo)
FGameplayAttributeData MaxRifleReserveAmmo;
ATTRIBUTE_ACCESSORS(UGSAmmoAttributeSet, MaxRifleReserveAmmo)
UPROPERTY(BlueprintReadOnly, Category = "Ammo", ReplicatedUsing = OnRep_RocketReserveAmmo)
FGameplayAttributeData RocketReserveAmmo;
ATTRIBUTE_ACCESSORS(UGSAmmoAttributeSet, RocketReserveAmmo)
...
使用DefaultObject
在 Unreal Engine 中,每个继承自 UObject
类的类都有一个默认对象,可以通过 GetDefaultObject
或 GetMutableDefault
函数获取。其中,GetDefaultObject
函数返回一个常量对象指针,不能修改该对象的属性值,而 GetMutableDefault
函数返回一个可修改的对象指针,可以修改该对象的属性值。
FORCEINLINE T* GetDefaultObject() const
{
UObject* Result = nullptr;
if (Class)
{
Result = Class->GetDefaultObject();
check(Result && Result->IsA(T::StaticClass()));
}
return (T*)Result;
}
UAIAgentSettings* const settings = GetMutableDefault<UAIAgentSettings>();
if (nullptr == settings)
{
return;
}
//获取设置类的默认值,几乎没有损耗
Comments NOTHING