UE4学习笔记(二):c++与蓝图的交互

  今天学习的是c++与蓝图的交互, 继续使用昨天的项目,在FloatingActor.h添加三个属性:
  

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage")
        int32 TotalDamage;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Damage")
        float DamageTimeInSeconds;

    UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Transient, Category = "Damage")
        float DamagePerSecond;
        //只读属性,通过TotalDamage与DamageTimeInSeconds来计算

用宏来包裹属性,BlueprintReadWrite代表将此属性暴露给蓝图,编译后就会在UE4中发现属性已经出现了:
UE4学习笔记(二):c++与蓝图的交互_第1张图片

然后我们给数据初始化:

void PostInitProperties();

UFUNCTION(BlueprintCallable, Category = "Damage")
//将CalculateValues()函数暴露在蓝图中
void CalculateValues();

void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent);
AFloatingActor::AFloatingActor() :
TotalDamage(300),
DamageTimeInSeconds(2.f)
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

}
void AFloatingActor::PostInitProperties()
{
    Super::PostInitProperties();

    CalculateValues();
}

void AFloatingActor::CalculateValues()
{
    DamagePerSecond = TotalDamage / DamageTimeInSeconds;
}

#if WITH_EDITOR
void AFloatingActor::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
    CalculateValues();

    Super::PostEditChangeProperty(PropertyChangedEvent);
}
#endif

  后面三个函数是用来初始化DamagePerSecond的,对于第三个函数我要说一下,如果没有第三个函数的话,DamagePerSecond将会只初始化一次,后面TotalDamage和DamageTimeInSeconds的值再修改它也不会变,这当然不是我们所希望的,此函数的作用是当属性发生变化时调用CalculateValues(),加上#if WITH_EDITOR就是当我们需要时DamagePerSecond才会重新计算,减少不必要的开销。
  然后我们就可以在UE4中创建一个继承自AFloatingActor的蓝图类了:
  UE4学习笔记(二):c++与蓝图的交互_第2张图片
UE4学习笔记(二):c++与蓝图的交互_第3张图片
  
  双击蓝图打开蓝图编辑器,这样就可以添加我们在AFloatingActor中写的函数了,如图,在蓝图中完成了DamagePerSecond的更新计算:
  UE4学习笔记(二):c++与蓝图的交互_第4张图片
  UE4学习笔记(二):c++与蓝图的交互_第5张图片
  

你可能感兴趣的:(UE4学习笔记)