C++ 在 Unreal 中为游戏增加实时音视频互动的教程详解

2020-05-29 11:02:26于丽

创建 EnterChannelWidget C++类

EnterChannelWidget是负责管理 UI 元素交互的。我们要创建一个新的 UserWidget 类型的类。在内容浏览器中,按Add New按钮,选择New C++类,然后勾选Show All Classes按钮,输入UserWidget。按下 "下一步 "按钮,为类设置一个名称,EnterChannelWidget。

我们会得到如下代码:

//EnterChannelWidget.h
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "EnterChannelWidget.generated.h"
UCLASS()
class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
{
 GENERATED_BODY()
};

在EnterChannelWidget.h文件中增加一些必要的 include:

//EnterCahnnelWidget.h
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "Components/TextBlock.h"
#include "Components/RichTextBlock.h"
#include "Components/EditableTextBox.h"
#include "Components/ComboBoxString.h"
#include "Components/Button.h"
#include "Components/Image.h"
#include "VideoCall.h"
#include "EnterChannelWidget.generated.h"
class AVideoCallPlayerController;
//EnterCahnnelWidget.cpp
#include "Blueprint/WidgetTree.h"
#include "VideoCallPlayerController.h"

然后我们需要增加如下变量:

//EnterChannelWidget.h
...
UCLASS()
class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
{
 GENERATED_BODY()
public:
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UTextBlock* HeaderTextBlock = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UTextBlock* DescriptionTextBlock = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UEditableTextBox* ChannelNameTextBox = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UEditableTextBox* EncriptionKeyTextBox = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UTextBlock* EncriptionTypeTextBlock = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UComboBoxString* EncriptionTypeComboBox = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UButton* JoinButton = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UButton* TestButton = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UButton* VideoSettingsButton = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UTextBlock* ContactsTextBlock = nullptr;
 UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
 UTextBlock* BuildInfoTextBlock = nullptr;
 ...
};

这些变量用来公职 blueprint asset 中相关的 UI 元素。这里最重要的是 BindWidget 元属性。通过将指向小部件的指针标记为 BindWidget,你可以在你的 C++类的 Blueprint 子类中创建一个同名的小部件,并在运行时从 C++中访问它。