feat: add L_LuaDemo scene and verify UnLua Tick, input, and hot-reload

This commit is contained in:
szy73711 committed 2026-11-28 15:48:35 +08:00
1 parent 943af16954
commit 256a60ac80
13 files changed
+667 -15

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
[/Script/EngineSettings.GameMapsSettings] [/Script/EngineSettings.GameMapsSettings]
GameDefaultMap=/Engine/Maps/Templates/Template_Default GameDefaultMap=/Game/Maps/L_LuaDemo
EditorStartupMap=/Engine/Maps/Templates/Template_Default EditorStartupMap=/Game/Maps/L_LuaDemo
GlobalDefaultGameMode=/Script/UnrealLuaDemo.LuaGameModeBase GlobalDefaultGameMode=/Script/UnrealLuaDemo.LuaGameModeBase
GameInstanceClass=/Script/UnrealLuaDemo.LuaGameInstance GameInstanceClass=/Script/UnrealLuaDemo.LuaGameInstance
Binary file not shown.
+45 -9
View File
@@ -8,8 +8,19 @@ local HotReload = {}
HotReload.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload" HotReload.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload"
HotReload.EVENT_AFTER_RELOAD = "Framework.AfterHotReload" HotReload.EVENT_AFTER_RELOAD = "Framework.AfterHotReload"
---Reloads a specific Lua module (clears package.loaded and re-requires it). local function CollectReloadableGameModules()
---@param moduleName string Dot-separated Lua module name, e.g. "Game.LuaGameMode" local modules = {}
for name, _ in pairs(package.loaded) do
if type(name) == "string" and name:match("^Game%.") then
modules[#modules + 1] = name
end
end
table.sort(modules)
return modules
end
---Reloads a specific Lua module using UnLua's hot-reload sandbox (falls back to package.loaded reset).
---@param moduleName string Dot-separated Lua module name, e.g. "Game.LuaDemoActor"
---@return boolean ok ---@return boolean ok
---@return any resultOrErr ---@return any resultOrErr
function HotReload.ReloadModule(moduleName) function HotReload.ReloadModule(moduleName)
@@ -20,25 +31,50 @@ function HotReload.ReloadModule(moduleName)
Log.Info("Hot-reloading Lua module: %s", moduleName) Log.Info("Hot-reloading Lua module: %s", moduleName)
EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, moduleName) EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, moduleName)
local okHr, unluaHr = pcall(require, "UnLua.HotReload")
if okHr and unluaHr and type(unluaHr.reload) == "function" then
local ok, err = pcall(unluaHr.reload, { moduleName })
if not ok then
Log.Error("UnLua.HotReload.reload('%s') failed: %s", moduleName, tostring(err))
return false, err
end
else
package.loaded[moduleName] = nil package.loaded[moduleName] = nil
local ok, result = pcall(require, moduleName) local ok, result = pcall(require, moduleName)
if not ok then if not ok then
Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result)) Log.Error("Failed to hot-reload module '%s': %s", moduleName, tostring(result))
return false, result return false, result
end end
EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, moduleName, result)
Log.Info("Successfully hot-reloaded Lua module: %s", moduleName)
return true, result
end end
---Triggers UnLua's built-in hot reload across all loaded modules. EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, moduleName)
Log.Info("Successfully hot-reloaded Lua module: %s", moduleName)
return true
end
---Triggers UnLua hot-reload across all loaded Game.* modules (supports Saved/HotUpdate/Script overrides).
---@return boolean ok ---@return boolean ok
function HotReload.ReloadAll() function HotReload.ReloadAll()
Log.Info("Triggering full UnLua HotReload...") local gameModules = CollectReloadableGameModules()
Log.Info("Triggering UnLua HotReload (modules=%d)...", #gameModules)
EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, "*") EventBus.Emit(HotReload.EVENT_BEFORE_RELOAD, "*")
if UnLua and type(UnLua.HotReload) == "function" then local okHr, unluaHr = pcall(require, "UnLua.HotReload")
if okHr and unluaHr and type(unluaHr.reload) == "function" then
if #gameModules > 0 then
local ok, err = pcall(unluaHr.reload, gameModules)
if not ok then
Log.Error("UnLua.HotReload.reload(gameModules) failed: %s", tostring(err))
return false
end
end
-- Also run timestamp-based check for any other modified modules
local ok2, err2 = pcall(unluaHr.reload)
if not ok2 then
Log.Error("UnLua.HotReload.reload() failed: %s", tostring(err2))
return false
end
elseif UnLua and type(UnLua.HotReload) == "function" then
local ok, err = pcall(UnLua.HotReload) local ok, err = pcall(UnLua.HotReload)
if not ok then if not ok then
Log.Error("UnLua.HotReload() failed: %s", tostring(err)) Log.Error("UnLua.HotReload() failed: %s", tostring(err))
+109
View File
@@ -0,0 +1,109 @@
---@type LuaDemoActor
local M = UnLua.Class()
local Log = require("Framework.Log")
local EventBus = require("Framework.EventBus")
local HotReload = require("Framework.HotReload")
local DEMO_COLORS = {
{ Name = "Cyan", R = 0.08, G = 0.78, B = 0.95, A = 1.0 },
{ Name = "Gold", R = 0.98, G = 0.72, B = 0.12, A = 1.0 },
{ Name = "Magenta", R = 0.92, G = 0.22, B = 0.65, A = 1.0 },
{ Name = "Lime", R = 0.25, G = 0.90, B = 0.35, A = 1.0 },
{ Name = "Orange", R = 0.98, G = 0.42, B = 0.14, A = 1.0 },
}
local function MakeLinearColor(c)
return UE.FLinearColor(c.R, c.G, c.B, c.A)
end
function M:ReceiveBeginPlay()
self.ElapsedTime = 0.0
self.TextRefreshTimer = 0.0
self.TickCount = 0
self.PingCount = 0
self.ReloadCount = 0
self.ColorIndex = 1
self.HasLoggedTick = false
EventBus.On("Demo.Ping", self.OnDemoPing, self)
EventBus.On(HotReload.EVENT_AFTER_RELOAD, self.OnAfterHotReload, self)
self:ApplyCurrentColor()
self:RefreshStatusText()
Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION)
local msg = string.format("[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping, [R] to HotReload", _VERSION)
UE.UKismetSystemLibrary.PrintString(self, msg, true, true, UE.FLinearColor(0.2, 1.0, 0.4, 1.0), 8.0)
end
function M:ReceiveTick(DeltaSeconds)
self.ElapsedTime = (self.ElapsedTime or 0.0) + DeltaSeconds
self.TickCount = (self.TickCount or 0) + 1
if not self.HasLoggedTick then
self.HasLoggedTick = true
Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds)
end
-- Rotate cube mesh & apply vertical sine-wave bobbing entirely from Lua
local yawDelta = (self.SpinSpeed or 60.0) * DeltaSeconds
local pitchDelta = yawDelta * 0.35
self:AddCubeLocalRotation(UE.FRotator(pitchDelta, yawDelta, 0.0))
local zOffset = math.sin(self.ElapsedTime * (self.BobFrequency or 2.0)) * (self.BobAmplitude or 25.0)
self:SetCubeVerticalOffset(zOffset)
self.TextRefreshTimer = (self.TextRefreshTimer or 0.0) + DeltaSeconds
if self.TextRefreshTimer >= 0.2 then
self.TextRefreshTimer = 0.0
self:RefreshStatusText()
end
end
function M:OnDemoPing(sourceName)
self.PingCount = (self.PingCount or 0) + 1
self.ColorIndex = (self.ColorIndex % #DEMO_COLORS) + 1
local colorEntry = self:ApplyCurrentColor()
self:RefreshStatusText()
local msg = string.format("[UnLua Demo] Ping #%d from %s -> Cube color: %s", self.PingCount, tostring(sourceName), colorEntry.Name)
Log.Info(msg)
UE.UKismetSystemLibrary.PrintString(self, msg, true, true, MakeLinearColor(colorEntry), 3.0)
end
function M:OnAfterHotReload(moduleName)
self.ReloadCount = (self.ReloadCount or 0) + 1
self:RefreshStatusText()
local msg = string.format("[UnLua Demo] HotReload #%d completed (target=%s)", self.ReloadCount, tostring(moduleName))
Log.Info(msg)
UE.UKismetSystemLibrary.PrintString(self, msg, true, true, UE.FLinearColor(1.0, 0.85, 0.2, 1.0), 4.0)
end
function M:ApplyCurrentColor()
local colorEntry = DEMO_COLORS[self.ColorIndex or 1] or DEMO_COLORS[1]
self:SetCubeColor(MakeLinearColor(colorEntry))
return colorEntry
end
function M:RefreshStatusText()
local colorEntry = DEMO_COLORS[self.ColorIndex or 1] or DEMO_COLORS[1]
local text = string.format(
"UnLua Active (%s)\nTime: %.1fs | Pings: %d | Reloads: %d | Color: %s\n[Space] Ping Lua | [R] HotReload",
_VERSION,
self.ElapsedTime or 0.0,
self.PingCount or 0,
self.ReloadCount or 0,
colorEntry.Name
)
self:SetStatusText(text)
end
function M:ReceiveEndPlay(EndPlayReason)
EventBus.OffAllForOwner(self)
Log.Info("LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d)", self.TickCount or 0, self.PingCount or 0)
end
return M
+9 -1
View File
@@ -4,7 +4,15 @@ local M = UnLua.Class()
local Log = require("Framework.Log") local Log = require("Framework.Log")
function M:ReceiveBeginPlay() function M:ReceiveBeginPlay()
Log.Info("LuaGameMode:ReceiveBeginPlay()") Log.Info("LuaGameMode:ReceiveBeginPlay() - Demo scene started")
UE.UKismetSystemLibrary.PrintString(
self,
"[UnLua Demo] LuaGameMode initialized!",
true,
true,
UE.FLinearColor(0.3, 0.85, 1.0, 1.0),
5.0
)
end end
function M:ReceiveEndPlay(EndPlayReason) function M:ReceiveEndPlay(EndPlayReason)
+13 -1
View File
@@ -2,9 +2,21 @@
local M = UnLua.Class() local M = UnLua.Class()
local Log = require("Framework.Log") local Log = require("Framework.Log")
local EventBus = require("Framework.EventBus")
local HotReload = require("Framework.HotReload")
function M:ReceiveBeginPlay() function M:ReceiveBeginPlay()
Log.Info("LuaPlayerController:ReceiveBeginPlay()") Log.Info("LuaPlayerController:ReceiveBeginPlay() - Ready for [Space]=Ping, [R]=HotReload")
end
function M:OnDemoPingPressed()
Log.Info("LuaPlayerController:OnDemoPingPressed() -> Emitting Demo.Ping")
EventBus.Emit("Demo.Ping", "LuaPlayerController")
end
function M:OnDemoHotReloadPressed()
Log.Info("LuaPlayerController:OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()")
HotReload.ReloadAll()
end end
function M:ReceiveEndPlay(EndPlayReason) function M:ReceiveEndPlay(EndPlayReason)
+17 -2
View File
@@ -8,17 +8,20 @@
UnrealLuaDemo/ UnrealLuaDemo/
├── Config/ # UE 项目配置(DefaultEngine / DefaultGame / DefaultInput 等) ├── Config/ # UE 项目配置(DefaultEngine / DefaultGame / DefaultInput 等)
├── Content/ ├── Content/
│ ├── Maps/
│ │ └── L_LuaDemo.umap # Lua 执行与热更新验证 Demo 关卡(默认启动地图)
│ └── Script/ # Lua 脚本根目录(打包时通过 DirectoriesToAlwaysStageAsNonUFS 输出) │ └── Script/ # Lua 脚本根目录(打包时通过 DirectoriesToAlwaysStageAsNonUFS 输出)
│ ├── Framework/ # Lua 基础框架层 │ ├── Framework/ # Lua 基础框架层
│ │ ├── Bootstrap.lua # 框架启动入口(由 LuaGameInstance 初始化) │ │ ├── Bootstrap.lua # 框架启动入口(由 LuaGameInstance 初始化)
│ │ ├── EventBus.lua # 轻量级事件总线 │ │ ├── EventBus.lua # 轻量级事件总线
│ │ ├── HotReload.lua # Lua 模块热重载协调器 │ │ ├── HotReload.lua # Lua 模块热重载协调器
│ │ └── Log.lua # 统一日志封装 │ │ └── Log.lua # 统一日志封装
│ └── Game/ # 游戏核心类对应的 Lua 绑定脚本 │ └── Game/ # 游戏核心类与 Demo 对应的 Lua 绑定脚本
│ ├── LuaGameInstance.lua │ ├── LuaGameInstance.lua
│ ├── LuaGameMode.lua │ ├── LuaGameMode.lua
│ ├── LuaPlayerController.lua │ ├── LuaPlayerController.lua
│ └── LuaCharacter.lua │ ├── LuaCharacter.lua
│ └── LuaDemoActor.lua # Demo 场景中的旋转立方体与 3D 状态文本控制脚本
├── Plugins/ ├── Plugins/
│ └── UnLua/ # Tencent UnLua 插件(已适配 UE 5.8 编译) │ └── UnLua/ # Tencent UnLua 插件(已适配 UE 5.8 编译)
├── Source/ ├── Source/
@@ -31,13 +34,25 @@ UnrealLuaDemo/
│ │ ├── LuaPlayerController.* │ │ ├── LuaPlayerController.*
│ │ ├── LuaCharacter.* │ │ ├── LuaCharacter.*
│ │ └── LuaBlueprintLibrary.* │ │ └── LuaBlueprintLibrary.*
│ ├── Demo/ # 验证场景 Actor
│ │ └── LuaDemoActor.*
│ └── HotUpdate/ # Lua 热更新子系统 │ └── HotUpdate/ # Lua 热更新子系统
│ └── LuaHotUpdateSubsystem.* │ └── LuaHotUpdateSubsystem.*
├── Tools/
│ └── create_demo_map.py # UE Python 关卡生成脚本(可重建 L_LuaDemo.umap)
├── .gitignore ├── .gitignore
├── .gitattributes ├── .gitattributes
└── UnrealLuaDemo.uproject └── UnrealLuaDemo.uproject
``` ```
## Demo 场景验证(`L_LuaDemo`)
打开 `UnrealLuaDemo.uproject` 后会自动加载默认关卡 `Content/Maps/L_LuaDemo.umap`,点击 **Play (PIE)** 即可验证:
- **自动执行验证**:场景中正前方的 `LuaDemoActor` 由 `Content/Script/Game/LuaDemoActor.lua` 驱动,会自动旋转、上下浮动,并在上方 3D 文本实时刷新 Lua 版本、运行时间、Ping 次数、热重载次数与当前颜色,同时屏幕左上角打印初始化信息。
- **按 `Space`(空格)**:验证 `C++ 输入 -> LuaPlayerController -> EventBus -> LuaDemoActor -> C++ 材质颜色/3D 文本` 全链路,立方体切换颜色且计数 +1。
- **按 `R`**:触发全量 Lua 热重载(`HotReload.ReloadAll()`),热重载计数 +1;可先将修改后的脚本放到 `Saved/HotUpdate/Script/Game/LuaDemoActor.lua` 再按 `R` 直接验证热更新覆盖生效。
## 核心设计 ## 核心设计
1. **C++ 骨架 + Lua 业务分离** 1. **C++ 骨架 + Lua 业务分离**
@@ -1,8 +1,134 @@
// Copyright Epic Games, Inc. All Rights Reserved. // Copyright Epic Games, Inc. All Rights Reserved.
#include "Core/LuaPlayerController.h" #include "Core/LuaPlayerController.h"
#include "Demo/LuaDemoActor.h"
#include "UnrealLuaDemo.h"
#include "Components/InputComponent.h"
#include "Engine/World.h"
#include "EngineUtils.h"
#include "InputCoreTypes.h"
#include "InputKeyEventArgs.h"
#include "TimerManager.h"
void ALuaPlayerController::BeginPlay()
{
Super::BeginPlay();
bShowMouseCursor = false;
FInputModeGameOnly InputMode;
SetInputMode(InputMode);
}
void ALuaPlayerController::SetupInputComponent()
{
Super::SetupInputComponent();
if (InputComponent)
{
FInputKeyBinding& PingBinding = InputComponent->BindKey(EKeys::SpaceBar, IE_Pressed, this, &ALuaPlayerController::HandlePingKeyPressed);
PingBinding.bConsumeInput = false;
FInputKeyBinding& ReloadBinding = InputComponent->BindKey(EKeys::R, IE_Pressed, this, &ALuaPlayerController::HandleHotReloadKeyPressed);
ReloadBinding.bConsumeInput = false;
}
}
FString ALuaPlayerController::GetModuleName_Implementation() const FString ALuaPlayerController::GetModuleName_Implementation() const
{ {
return LuaModuleName; return LuaModuleName;
} }
void ALuaPlayerController::HandlePingKeyPressed()
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua"));
OnDemoPingPressed();
}
void ALuaPlayerController::HandleHotReloadKeyPressed()
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua"));
OnDemoHotReloadPressed();
}
void ALuaPlayerController::DemoVerifyInteraction()
{
UWorld* World = GetWorld();
if (!World)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Scheduling simulated SpaceBar and R key presses after world ticks..."));
FTimerHandle Step1Handle;
World->GetTimerManager().SetTimer(Step1Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 1: Simulating SpaceBar Pressed/Released"));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Pressed, 1.0f));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Released, 0.0f));
}, 0.35f, false);
FTimerHandle Step2Handle;
World->GetTimerManager().SetTimer(Step2Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 2: Simulating R Pressed/Released"));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Pressed, 1.0f));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Released, 0.0f));
}, 0.70f, false);
FTimerHandle Step3Handle;
World->GetTimerManager().SetTimer(Step3Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC || !PC->GetWorld())
{
return;
}
ALuaDemoActor* DemoActor = nullptr;
if (TActorIterator<ALuaDemoActor> It(PC->GetWorld()); It)
{
DemoActor = *It;
}
if (!DemoActor)
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: ALuaDemoActor not found in world."));
FPlatformMisc::RequestExitWithStatus(false, 1);
return;
}
const FString StatusStr = DemoActor->GetStatusTextString();
const FRotator CubeRot = DemoActor->GetCubeLocalRotation();
const bool bHasTickRotation = !CubeRot.IsNearlyZero();
const bool bHasPing = StatusStr.Contains(TEXT("Pings: 1"));
const bool bHasReload = StatusStr.Contains(TEXT("Reloads: 1"));
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 3 Result -> CubeRot=%s | StatusText=\n%s"),
*CubeRot.ToString(), *StatusStr);
if (bHasTickRotation && bHasPing && bHasReload)
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] PASSED: Tick rotation, SpaceBar Ping, and R HotReload all verified!"));
PC->ConsoleCommand(TEXT("Quit"));
}
else
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: TickRot=%d Ping=%d Reload=%d"),
bHasTickRotation ? 1 : 0, bHasPing ? 1 : 0, bHasReload ? 1 : 0);
FPlatformMisc::RequestExitWithStatus(false, 1);
}
}, 1.15f, false);
}
@@ -9,6 +9,7 @@
/** /**
* Base PlayerController bound to Lua (Content/Script/Game/LuaPlayerController.lua). * Base PlayerController bound to Lua (Content/Script/Game/LuaPlayerController.lua).
* Binds demo hotkeys ([Space] Ping Lua, [R] HotReload Lua) and forwards them to Lua via BlueprintImplementableEvent.
*/ */
UCLASS() UCLASS()
class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public IUnLuaInterface class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public IUnLuaInterface
@@ -16,9 +17,31 @@ class UNREALLUADEMO_API ALuaPlayerController : public APlayerController, public
GENERATED_BODY() GENERATED_BODY()
public: public:
virtual void BeginPlay() override;
virtual void SetupInputComponent() override;
virtual FString GetModuleName_Implementation() const override; virtual FString GetModuleName_Implementation() const override;
/**
* Implemented in LuaPlayerController.lua to test C++ -> Lua -> EventBus flow.
* Note: BlueprintImplementableEvent ensures UE always dispatches through ProcessEvent into UnLua
* (unlike BlueprintNativeEvent on native C++ classes which UHT optimizes to bypass ProcessEvent).
*/
UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo")
void OnDemoPingPressed();
/** Implemented in LuaPlayerController.lua to trigger live Lua hot-reload. */
UFUNCTION(BlueprintImplementableEvent, Category = "LuaDemo")
void OnDemoHotReloadPressed();
/** Automated self-test command (console: Demo.VerifyInteraction) that simulates Space & R and verifies Tick + Lua state. */
UFUNCTION(Exec)
void DemoVerifyInteraction();
protected: protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaPlayerController"); FString LuaModuleName = TEXT("Game.LuaPlayerController");
private:
void HandlePingKeyPressed();
void HandleHotReloadKeyPressed();
}; };
+119
View File
@@ -0,0 +1,119 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Demo/LuaDemoActor.h"
#include "Components/StaticMeshComponent.h"
#include "Components/TextRenderComponent.h"
#include "Engine/StaticMesh.h"
#include "Materials/MaterialInterface.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "UObject/ConstructorHelpers.h"
ALuaDemoActor::ALuaDemoActor()
{
PrimaryActorTick.bCanEverTick = true;
SceneRoot = CreateDefaultSubobject<USceneComponent>(TEXT("SceneRoot"));
SetRootComponent(SceneRoot);
CubeMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("CubeMesh"));
CubeMesh->SetupAttachment(SceneRoot);
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeMeshAsset(TEXT("/Engine/BasicShapes/Cube.Cube"));
if (CubeMeshAsset.Succeeded())
{
CubeMesh->SetStaticMesh(CubeMeshAsset.Object);
}
static ConstructorHelpers::FObjectFinder<UMaterialInterface> BasicMatAsset(TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial"));
if (BasicMatAsset.Succeeded())
{
CubeMesh->SetMaterial(0, BasicMatAsset.Object);
}
StatusText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("StatusText"));
StatusText->SetupAttachment(SceneRoot);
StatusText->SetRelativeLocation(FVector(0.0f, 0.0f, 120.0f));
// Face -X toward PlayerStart placed at (-450, 0, 100)
StatusText->SetRelativeRotation(FRotator(0.0f, 180.0f, 0.0f));
StatusText->SetHorizontalAlignment(EHTA_Center);
StatusText->SetVerticalAlignment(EVRTA_TextCenter);
StatusText->SetWorldSize(26.0f);
StatusText->SetTextRenderColor(FColor(120, 245, 255));
StatusText->SetText(FText::FromString(TEXT("Waiting for UnLua...")));
}
void ALuaDemoActor::BeginPlay()
{
InitialLocation = GetActorLocation();
if (CubeMesh)
{
CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0);
}
Super::BeginPlay();
}
void ALuaDemoActor::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
// AActor::Tick skips ReceiveTick for pure native C++ classes (CLASS_Native without CLASS_CompiledFromBlueprint).
// Explicitly call ReceiveTick so UnLua's Lua ReceiveTick override executes every frame.
if (!GetClass()->HasAnyClassFlags(CLASS_CompiledFromBlueprint))
{
ReceiveTick(DeltaSeconds);
}
}
FString ALuaDemoActor::GetModuleName_Implementation() const
{
return LuaModuleName;
}
void ALuaDemoActor::SetStatusText(const FString& InText)
{
if (StatusText)
{
StatusText->SetText(FText::FromString(InText));
}
}
FString ALuaDemoActor::GetStatusTextString() const
{
return StatusText ? StatusText->Text.ToString() : FString();
}
void ALuaDemoActor::SetCubeColor(FLinearColor NewColor)
{
if (!CubeDynamicMaterial && CubeMesh)
{
CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0);
}
if (CubeDynamicMaterial)
{
CubeDynamicMaterial->SetVectorParameterValue(TEXT("Color"), NewColor);
}
}
void ALuaDemoActor::AddCubeLocalRotation(FRotator DeltaRotation)
{
if (CubeMesh)
{
CubeMesh->AddLocalRotation(DeltaRotation);
}
}
FRotator ALuaDemoActor::GetCubeLocalRotation() const
{
return CubeMesh ? CubeMesh->GetRelativeRotation() : FRotator::ZeroRotator;
}
void ALuaDemoActor::SetCubeVerticalOffset(float ZOffset)
{
if (CubeMesh)
{
CubeMesh->SetRelativeLocation(FVector(0.0f, 0.0f, ZOffset));
}
}
+86
View File
@@ -0,0 +1,86 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "UnLuaInterface.h"
#include "LuaDemoActor.generated.h"
class UStaticMeshComponent;
class UTextRenderComponent;
class UMaterialInstanceDynamic;
/**
* Interactive demo actor driven by Lua (Content/Script/Game/LuaDemoActor.lua)
* to visually and programmatically verify UnLua binding, Tick, EventBus, and HotReload.
*/
UCLASS(Blueprintable)
class UNREALLUADEMO_API ALuaDemoActor : public AActor, public IUnLuaInterface
{
GENERATED_BODY()
public:
ALuaDemoActor();
virtual void BeginPlay() override;
virtual void Tick(float DeltaSeconds) override;
virtual FString GetModuleName_Implementation() const override;
/** Updates the floating 3D status text rendered above the cube. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetStatusText(const FString& InText);
/** Returns the current floating 3D status text string. */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FString GetStatusTextString() const;
/** Updates the dynamic material color of the demo cube. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetCubeColor(FLinearColor NewColor);
/** Returns the world location captured at BeginPlay (used for smooth bobbing). */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FVector GetInitialLocation() const { return InitialLocation; }
/** Rotates only the cube mesh while keeping the floating 3D label readable. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void AddCubeLocalRotation(FRotator DeltaRotation);
/** Returns the current relative rotation of the cube mesh. */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FRotator GetCubeLocalRotation() const;
/** Sets the vertical bob offset of the cube mesh relative to the actor root. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetCubeVerticalOffset(float ZOffset);
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<USceneComponent> SceneRoot;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<UStaticMeshComponent> CubeMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<UTextRenderComponent> StatusText;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float SpinSpeed = 60.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float BobAmplitude = 25.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float BobFrequency = 2.0f;
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaDemoActor");
private:
UPROPERTY(Transient)
TObjectPtr<UMaterialInstanceDynamic> CubeDynamicMaterial;
FVector InitialLocation = FVector::ZeroVector;
};
+111
View File
@@ -0,0 +1,111 @@
import unreal
MAP_PATH = "/Game/Maps/L_LuaDemo"
def main():
level_sub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
actor_sub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
unreal.log(f"[CreateDemoMap] Creating level: {MAP_PATH}")
ok = level_sub.new_level(MAP_PATH)
if not ok:
raise RuntimeError(f"Failed to create new level at {MAP_PATH}")
# 1. Floor plane with grid material
floor = actor_sub.spawn_actor_from_class(
unreal.StaticMeshActor,
unreal.Vector(0.0, 0.0, 0.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
floor.set_actor_label("DemoFloor")
floor.set_actor_scale3d(unreal.Vector(25.0, 25.0, 1.0))
plane_mesh = unreal.EditorAssetLibrary.load_asset("/Engine/BasicShapes/Plane")
if plane_mesh:
floor.static_mesh_component.set_static_mesh(plane_mesh)
grid_mat = unreal.EditorAssetLibrary.load_asset("/Engine/EngineMaterials/WorldGridMaterial")
if grid_mat:
floor.static_mesh_component.set_material(0, grid_mat)
# 2. Directional sun light
sun = actor_sub.spawn_actor_from_class(
unreal.DirectionalLight,
unreal.Vector(0.0, 0.0, 500.0),
unreal.Rotator(-45.0, -35.0, 0.0),
)
sun.set_actor_label("DemoSunLight")
sun_comp = sun.light_component
sun_comp.set_mobility(unreal.ComponentMobility.MOVABLE)
sun_comp.set_intensity(4.0)
try:
sun_comp.set_editor_property("atmosphere_sun_light", True)
except Exception:
pass
# 3. SkyLight
sky_light = actor_sub.spawn_actor_from_class(
unreal.SkyLight,
unreal.Vector(0.0, 0.0, 600.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
sky_light.set_actor_label("DemoSkyLight")
sky_comp = sky_light.light_component
sky_comp.set_mobility(unreal.ComponentMobility.MOVABLE)
try:
sky_comp.set_editor_property("real_time_capture", True)
except Exception:
pass
# 4. SkyAtmosphere & ExponentialHeightFog
sky_atmo = actor_sub.spawn_actor_from_class(
unreal.SkyAtmosphere,
unreal.Vector(0.0, 0.0, 0.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
sky_atmo.set_actor_label("DemoSkyAtmosphere")
fog = actor_sub.spawn_actor_from_class(
unreal.ExponentialHeightFog,
unreal.Vector(0.0, 0.0, 0.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
fog.set_actor_label("DemoHeightFog")
# 5. PlayerStart facing +X toward LuaDemoActor
player_start = actor_sub.spawn_actor_from_class(
unreal.PlayerStart,
unreal.Vector(-450.0, 0.0, 100.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
player_start.set_actor_label("DemoPlayerStart")
# 6. LuaDemoActor driven by Content/Script/Game/LuaDemoActor.lua
demo_actor_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaDemoActor")
if demo_actor_class is None:
raise RuntimeError("Could not load /Script/UnrealLuaDemo.LuaDemoActor")
demo_actor = actor_sub.spawn_actor_from_class(
demo_actor_class,
unreal.Vector(0.0, 0.0, 140.0),
unreal.Rotator(0.0, 0.0, 0.0),
)
demo_actor.set_actor_label("LuaDemoActor")
# 7. Set level GameMode override to ALuaGameModeBase
world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()
if world:
ws = world.get_world_settings()
gm_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaGameModeBase")
if ws and gm_class:
ws.set_editor_property("default_game_mode", gm_class)
saved = level_sub.save_current_level()
if not saved:
raise RuntimeError(f"Failed to save level {MAP_PATH}")
unreal.log(f"[CreateDemoMap] Successfully created and saved {MAP_PATH}")
if __name__ == "__main__":
main()
+7
View File
@@ -21,6 +21,13 @@
"TargetAllowList": [ "TargetAllowList": [
"Editor" "Editor"
] ]
},
{
"Name": "PythonScriptPlugin",
"Enabled": true,
"TargetAllowList": [
"Editor"
]
} }
] ]
} }