为什么要GetWorld()?
在 Unreal 里会频繁看到 GetWorld(),原因是很多引擎功能都不是“全局静态”的,而是属于某个 World(关卡 / 游戏实例)上下文,必须拿到对应的 UWorld* 才能访问这些功能。
为什么要 GetWorld()?(本质)
UWorld 是引擎里表示一个世界/关卡实例的核心对象。它包含并管理:
当前关卡里的 Actor 列表(Spawn/Destroy Actor)
Tick / Timer 系统(
GetTimerManager())网络角色(GameMode/GameState/PlayerState)
玩家控制器(PlayerController)、本地玩家(LocalPlayer)
场景中的物理、导航、子系统等
很多 API 都需要知道“对哪个世界/关卡执行操作”,所以函数签名里会需要 UWorld* 或需要通过 GetWorld() 来推断出上下文。
GetWorld() 的常见用途举例
生成/销毁 Actor
GetWorld()->SpawnActor<AActor>(MyBPClass, Location, Rotation);设置定时器
GetWorld()->GetTimerManager().SetTimer(MyTimerHandle, this, &ThisClass::MyFunc, 1.0f, true);获取 PlayerController / Pawn / HUD
APlayerController* PC = GetWorld()->GetFirstPlayerController();开始 ServerTravel / Open Level(在 Server 上)
GetWorld()->ServerTravel("/Game/Maps/MyMap?listen");访问 GameMode / GameState / GameInstance
AGameModeBase* GM = GetWorld()->GetAuthGameMode(); UGameInstance* GI = GetWorld()->GetGameInstance();
