# 【使用委托】
- 定义委托和定义委托回调函数。
- 在构造函数里初始化委托和回调函数。
- 使用委托。
# 使用示例
MenuSystemCharacter.h
protected:
UFUNCTION(BlueprintCallable)
void CreateGameSession();
// 第一步A:定义委托回调函数
void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful);
private:
// 第一步B:定义委托
FOnCreateSessionCompleteDelegate CreateSessionCompleteDelegate;
MenuSystemCharacter.cpp
#include "OnlineSubsystem.h"
#include "OnlineSessionSettings.h"
DEFINE_LOG_CATEGORY(LogTemplateCharacter);
//////////////////////////////////////////////////////////////////////////
// AMenuSystemCharacter
// 第二步:初始化委托与回调
AMenuSystemCharacter::AMenuSystemCharacter():
CreateSessionCompleteDelegate(FOnCreateSessionCompleteDelegate::CreateUObject(this,&AMenuSystemCharacter::OnCreateSessionComplete))
{
IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get();
if (OnlineSubsystem)
{
OnlineSessionInterface = OnlineSubsystem->GetSessionInterface();
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(
-1,
15.f,
FColor::Blue,
FString::Printf(TEXT("Found subsystem %s"), *OnlineSubsystem->GetSubsystemName().ToString())
);
}
}
}
void AMenuSystemCharacter::CreateGameSession()
{
// 当点击按键1时调用
if (!OnlineSessionInterface.IsValid())
{
return;
}
auto ExistingSession = OnlineSessionInterface->GetNamedSession(NAME_GameSession);
if (ExistingSession != nullptr)
{
OnlineSessionInterface->DestroySession(NAME_GameSession);
}
// 第三步:使用委托
OnlineSessionInterface->AddOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate);
TSharedPtr<FOnlineSessionSettings> SessionSettings = MakeShareable(new FOnlineSessionSettings());
SessionSettings->bIsLANMatch = false;
SessionSettings->NumPublicConnections = 4;
SessionSettings->bAllowJoinInProgress = true;
SessionSettings->bAllowJoinViaPresence = true;
SessionSettings->bShouldAdvertise = true;
SessionSettings->bUsesPresence = true;
const ULocalPlayer* LocalPlayer = GetWorld()->GetFirstLocalPlayerFromController();
OnlineSessionInterface->CreateSession(*LocalPlayer->GetPreferredUniqueNetId(), NAME_GameSession, *SessionSettings);
}
void AMenuSystemCharacter::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful)
{
if (bWasSuccessful)
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(
-1,
15.f,
FColor::Blue,
FString::Printf(TEXT("Created session success::%s"), *SessionName.ToString())
);
}
}
else
{
if (GEngine)
{
GEngine->AddOnScreenDebugMessage(
-1,
15.f,
FColor::Red,
FString::Printf(TEXT("Failed to create session"))
);
}
}
}