函数改写步骤
-
查看原有函数的返回值,在C++类头文件中添加相同返回值的同名函数(蓝图类型对应的C++类型见下文)
-
在刚刚写好的函数上面新增一行,填写UFUNTCTION预编译指令
UFUNCTION(BlueprintCallable, BlueprintPure) FVector GetMaxGrabLocation() const;
其中,BlueprintCallable是必选项,否则无法在蓝图中调用该函数
BlueprintPure是在蓝图中,将其作为纯函数解析。即使用时不会出现执行引脚。作用与在蓝图函数中勾选“纯函数”一致 -
编写函数体
这里可以根据原有的蓝图函数函数体编写,可能需要引入库。详见博文 -
在蓝图中删除原有的蓝图函数
蓝图变量类型对应的C++类型
普通数据类型
蓝图简化了C++的一些类型。比如蓝图中只有float没有double,整型只有int32和int64没有uint
工具类型(结构体)
C++中结构体以F开头
对象类型
继承自Object的在C++中均以U开头,除非其继承自Actor,此时以A开头
完整代码
.h
#pragma once
#include "CoreMinimal.h"
#include "Components/SceneComponent.h"
#include "Grabber.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent), Blueprintable )
class BLUEPRINTSTOCPP_API UGrabber : public USceneComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UGrabber();
protected:
// Called when the game starts
virtual void BeginPlay() override;
UFUNCTION(BlueprintCallable, BlueprintPure)
FVector GetMaxGrabLocation() const;
public:
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
protected:
UPROPERTY(EditAnywhere, BlueprintReadOnly)
float MaxGrabDistance = 100.0f;
};
.cpp
#include "Grabber.h"
#include "Kismet/KismetMathLibrary.h" //为了编写函数体引入的库
// Sets default values for this component's properties
UGrabber::UGrabber()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UGrabber::BeginPlay()
{
Super::BeginPlay();
// ...
}
FVector UGrabber::GetMaxGrabLocation() const
{
return GetComponentLocation() + UKismetMathLibrary::GetForwardVector(GetComponentRotation()) * MaxGrabDistance;
}
// Called every frame
void UGrabber::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}