一、UnLua调用C++全局静态函数
1、新建C++类MyLuaUtils,继承BlueprintFunctionLibrary,实现全局静态函数GetInt。
MyLuaUtils.h
UCLASS()
class LUASHOOTING_API UMyLuaUtils : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
UFUNCTION(BlueprintCallable)
static int GetInt();
};
MyLuaUtils.cpp
#include "MyLuaUtils.h"
int UMyLuaUtils::GetInt()
{
return 100;
}
2、修改《UnLua环境搭建》一文中的WBP_FirstLua脚本,调用MyLuaUtiles.GetInt函数。
WBP_FirstLua.lua
local WBP_FirstLua_C = UnLua.Class()
function WBP_FirstLua_C:Construct()
print('Hello UnLua:'..UE4.UMyLuaUtils.GetInt())
end
return WBP_FirstLua_C
3、运行查看Log。
二、UnLua调用C++成员函数
1、新建C++类MyBaseActor,继承Actor,实现GetIndex成员函数。
MyBaseActor.h
UCLASS()
class LUASHOOTING_API AMyBaseActor : public AActor
{
GENERATED_BODY()
public:
AMyBaseActor();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintCallable)
int GetIndex();
private:
int index;
};
MyBaseActor.cpp
int AMyBaseActor::GetIndex()
{
return index++;
}
2、新建蓝图类BP_BaseActor,继承C++类MyBaseActor,绑定Lua脚本BP_BaseActor.lua。
BP_BaseActor.lua
local BP_BaseActor_C = UnLua.Class()
function BP_BaseActor_C:ReceiveTick(DeltaSeconds)
print("Index:" .. self:GetIndex())
end
return BP_BaseActor_C
3、将蓝图BP_BaseActor拖到场景中创建一个实例,运行查看Log,每帧都在成功输出