Unreal Engine 4 虚幻引擎学习笔记(三)
UPROPERTY
可以带上分类属性,直接创建了Damage这个分类
UPROPERTY(EditAnywhere, Category="Damage")
int32 TotalDamage;
可见但不可编辑的属性
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Transient, Category = "Damage")
float DamagePerSecond;
Transient
表示不会保存到硬盘
构造函数初始化
下面2个程序功能一样:
AMyActor::AMyActor()
{
TotalDamage = 200;
DamageTimeInSeconds = 1.f;
}
AMyActor::AMyActor() :
TotalDamage(200),
DamageTimeInSeconds(1.f)
{
}
如果不手动初始化,引擎会自动设为0或空指针
可以根据TotalDamage与DamageTimeInSeconds对DamagePerSecond进行初始化
.h文件里加入
virtual void PostInitProperties() override;
.cpp文件里加入
void AMyActor::PostInitProperties()
{
Super::PostInitProperties();
DamagePerSecond = TotalDamage / DamageTimeInSeconds;
}
通过蓝图扩展C++类
上面的只是初始化,并不会实时计算DPS,要想实现,需作如下修改:
void AMyActor::PostInitProperties()
{
Super::PostInitProperties();
CalculateValues();
}
void AMyActor::CalculateValues()
{
DamagePerSecond = TotalDamage / DamageTimeInSeconds;
}
#if WITH_EDITOR
void AMyActor::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
CalculateValues();
Super::PostEditChangeProperty(PropertyChangedEvent);
}
#endif
其中if…endif这一段只是给编辑器用,并不会在游戏中生成.
使蓝图可从C++调用
只要在声明的语句前加上宏,如下:
UFUNCTION(BlueprintCallable, Category="Damage")
void CalculateValues();
使C++可从蓝图调用
UFUNCTION(BlueprintImplementableEvent, Category = "Damage")
void CalledFromCpp();
蓝图自己使用的方法
UFUNCTION(BlueprintNativeEvent, Category="Damage")
void CalledFromCpp();
宏里带有BlueprintNativeEvent
,必须在.cpp文件里写实现的方法,否则编译失败
void AMyActor::CalledFromCpp_Implementation()
{
// Do something cool here
}