了解 Unreal Engine 5 中的 Actor,创建并操控你的第一个 C++ 游戏对象!
在 Unreal Engine 5 中,Actor 是 游戏世界(World)中的基本对象,几乎所有的游戏元素(玩家、敌人、道具、灯光、摄像机等)都是 Actor 的子类。
Actor 的主要特点
在 UE5 C++ 中,Actor 继承自 AActor,并可以使用 UCLASS() 宏进行扩展。
新建 Actor 类
打开 MyFirstGameActor.cpp 和 MyFirstGameActor.h,让 Actor 在 BeginPlay() 时输出一条日志。
MyFirstGameActor.h(头文件)
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyFirstGameActor.generated.h"
UCLASS()
class MYFIRSTCPPGAME_API AMyFirstGameActor : public AActor
{
GENERATED_BODY()
public:
AMyFirstGameActor();
protected:
virtual void BeginPlay() override;
};
MyFirstGameActor.cpp(实现文件)
#include "MyFirstGameActor.h"
#include "Engine/Engine.h"
AMyFirstGameActor::AMyFirstGameActor()
{
PrimaryActorTick.bCanEverTick = true;
}
void AMyFirstGameActor::BeginPlay()
{
Super::BeginPlay();
UE_LOG(LogTemp, Warning, TEXT("Hello, this is my first Actor in Unreal Engine 5!"));
}
编译 C++ 代码
LogTemp: Warning: Hello, this is my first Actor in Unreal Engine 5!
✅ 你的第一个 C++ Actor 已成功运行!
Actor 在游戏中有 4 个主要生命周期阶段:
阶段 | 描述 |
---|---|
构造函数(Constructor) | Actor 生成时调用(用于初始化变量) |
BeginPlay() | 关卡开始运行时调用(适合初始化逻辑) |
Tick() | 每一帧都会调用(适用于更新逻辑) |
Destroy() | Actor 被销毁时调用(可执行清理工作) |
Tick() 示例
我们可以在 Tick() 函数中让 Actor 旋转:
void AMyFirstGameActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// 让 Actor 旋转
FRotator NewRotation = GetActorRotation();
NewRotation.Yaw += DeltaTime * 50.0f; // 每秒旋转 50 度
SetActorRotation(NewRotation);
}
这样 Actor 就会不断旋转,让游戏更生动!
Actor 本身是 空的,但我们可以为它 添加组件(Component),如:
我们可以在 MyFirstGameActor 中添加一个 立方体网格(Cube Mesh):
修改 MyFirstGameActor.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Components/StaticMeshComponent.h"
#include "MyFirstGameActor.generated.h"
UCLASS()
class MYFIRSTCPPGAME_API AMyFirstGameActor : public AActor
{
GENERATED_BODY()
public:
AMyFirstGameActor();
protected:
virtual void BeginPlay() override;
private:
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* MeshComponent;
};
修改 MyFirstGameActor.cpp
#include "MyFirstGameActor.h"
#include "Components/StaticMeshComponent.h"
#include "UObject/ConstructorHelpers.h"
AMyFirstGameActor::AMyFirstGameActor()
{
PrimaryActorTick.bCanEverTick = true;
// 创建 StaticMeshComponent 并设置为根组件
MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent"));
RootComponent = MeshComponent;
// 加载默认立方体模型
static ConstructorHelpers::FObjectFinder<UStaticMesh> MeshAsset(TEXT("/Engine/BasicShapes/Cube.Cube"));
if (MeshAsset.Succeeded())
{
MeshComponent->SetStaticMesh(MeshAsset.Object);
}
}
✅ 现在你的 Actor 终于有了外观!
问题 | 解决方案 |
---|---|
Actor 不能拖入场景 | 确保已 编译代码,并且 C++ 类 继承自 AActor |
UE_LOG 没有输出 | 确保 开启输出日志(Output Log) |
立方体网格未显示 | 检查路径 /Engine/BasicShapes/Cube.Cube 是否正确 |
✅ 理解 Actor 在 UE5 中的作用
✅ 创建 & 使用你的第一个 C++ Actor
✅ 实现 Actor 的生命周期方法(BeginPlay / Tick)
✅ 为 Actor 添加组件(Static Mesh)
恭喜你完成 UE5 C++ Actor 学习! 明天我们将深入 组件(Component)系统,让 Actor 更加强大!
记得收藏专栏,每天进步一点,最终独立开发属于你的 UE5 游戏!