04 蓝图与 C++ 协作:实现一台可复制终端

用蓝图与 C++ 协作实现可复制的中继终端。

手册总目录 · 模块 01 工程与框架

章节重点 用接口请求行为,用可复制属性表达持久状态,用可重入的表现函数驱动灯光。蓝图与 C++ 两条路线实现同一约定,任选一条。

蓝图路线。 创建 BPI_RelayInteract,加入无返回值的 Interact,输入 Interactor 为 Actor。创建 Actor 蓝图 BP_Relay,加入 Static Mesh 和 Point Light,打开 Class Defaults → Replicates,实例变量 RelayId 可编辑,布尔 bPowered 为 RepNotify,默认 false。实现接口事件时在 Authority 分支检查 bPowered;首次成功设为 true,并向当前 BP_RelayMode.RegisterRestored(RelayId) 登记。OnRep_bPowered 调 ApplyVisuals,BeginPlay 也调用一次。ApplyVisuals 按布尔值设置灯颜色与强度。默认值可以用冷灰和暖黄,断电时仍保留终端网格。此处接口是本机调用;第 06 章提供跨网络入口。

C++ 路线。 在名为 RelayLab 的 Runtime 模块中新建 Actor 子类。以下两个文件构成同一个类,依赖模板已有的 Core、CoreUObject、Engine。更换工程名时将 RELAYLAB_API 换成本模块的导出宏。功能限于终端的状态和表现回调,玩家请求与关卡计分仍按本节下方接线。

// RelaySwitch.h
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "RelaySwitch.generated.h"

UCLASS()
class RELAYLAB_API ARelaySwitch : public AActor
{
    GENERATED_BODY()

public:
    ARelaySwitch();

    UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="Relay")
    bool TryPowerOn();

protected:
    virtual void BeginPlay() override;
    virtual void GetLifetimeReplicatedProps(
        TArray<FLifetimeProperty>& OutLifetimeProps) const override;

    UFUNCTION(BlueprintImplementableEvent, Category="Relay")
    void ApplyPowerVisuals(bool bIsPowered);

private:
    UPROPERTY(ReplicatedUsing=OnRep_Powered)
    bool bPowered = false;

    UFUNCTION()
    void OnRep_Powered();
};
// RelaySwitch.cpp
#include "RelaySwitch.h"
#include "Components/SceneComponent.h"
#include "Net/UnrealNetwork.h"

ARelaySwitch::ARelaySwitch()
{
    bReplicates = true;
    SetRootComponent(CreateDefaultSubobject<USceneComponent>(TEXT("Root")));
}

void ARelaySwitch::BeginPlay()
{
    Super::BeginPlay();
    ApplyPowerVisuals(bPowered);
}

bool ARelaySwitch::TryPowerOn()
{
    if (!HasAuthority() || bPowered)
    {
        return false;
    }
    bPowered = true;
    ApplyPowerVisuals(bPowered);
    return true;
}

void ARelaySwitch::OnRep_Powered()
{
    ApplyPowerVisuals(bPowered);
}

void ARelaySwitch::GetLifetimeReplicatedProps(
    TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);
    DOREPLIFETIME(ARelaySwitch, bPowered);
}

从 ARelaySwitch 建蓝图子类,仍命名为 BP_Relay,在其中添加网格、灯和可编辑的 RelayId。将 Event Apply Power Visuals 的入参接到颜色选择。实现同一 BPI_RelayInteract:Interact → TryPowerOn → Branch(Return Value),仅在 True 时向 Mode 登记;这里不再声明第二份通电布尔。已有纯蓝图版本时,先在工程副本替换父类并清理旧状态。两条路线都在写入通电状态前检查 RelayId 在该关名单内,避免错误 ID 出现亮灯却不计数。将三台有效 ID 的终端置入地图。

排错实验 把“播放一次火花”直接接入 ApplyPowerVisuals,让新客户端进已通电房间,会把历史通电误演成现场事件。把稳定的灯状态与瞬间火花拆开。C++ 直接修改成员时显式刷新主机表现;蓝图变量的 Set 与 C++ 的赋值在 RepNotify 本机行为上要分别判断。

章节回顾 TryPowerOn 的返回值表达“这次是否真的发生了状态转换”。这条约定同时解决重复计分和重复触发特效,接口允许输入端不依赖具体终端类。

测试题

  1. 接口消息是否自动复制到服务器?
  2. C++ 主机控制台显示 bPowered=true,但灯仍暗,客户端正常,优先检查什么?
  3. 为何首次 BeginPlay 也应用表现?

官方研读 Blueprint Interface · Event Dispatcher · 属性复制与 RepNotify · 本仓库 UE C++ 接口笔记


← 03 Gameplay框架与规则 · 手册总目录 · 05 增强输入与射线交互 →