p20 首先我们现在有一个多人游戏的系统类MultiplayerSessionsSubsystem
在这个系统内提供了很多会话系统的接口SessionInterface
当现在我们有一些SessionInterfaceDelegates的委托,这个委托的来源是SessionInterface,所以我们使用的委托可以接收到来自SessionInterface的消息(回调/Callbacks)
在上节课,我们创建了菜单类MenuClass,调用的是MultiplayerSessionsSubsystem的函数
当我们在菜单类调用MultiplayerSessionsSubsystem的函数的时候,实际上是调用了SessionInterface的接口函数,这个时候SessionInterface就会通过SessionInterfaceDelegates这个委托给MultiplayerSessionsSubsystem发送消息(也就是回调,Callback Responds)
但是这个时候问题出现了,我们没有办法把SessionInterface返回给MultlplayerSubsystem内的消息(也就是CallbackResponds)发送给MenuClass
解决这个问题的方法是创建属于我们自己的委托,用来接受从MultiPlayerSubsystem返回来的消息
理解了含义后就可以开始学习了
Menu.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" #include "BaseMenu.generated.h" /** * */ class UButton; UCLASS() class MULTIPLAYERSESSION_API UBaseMenu : public UUserWidget { GENERATED_BODY() protected: virtual bool Initialize() override; virtual void NativeDestruct() override; /*这里创建用来对应MultiPlayerOnCreateSessionComplete的函数*/ UFUNCTION() void OnCreateSession(bool bWasSuccessful); public: UFUNCTION(BlueprintCallable) void MenuSetup(int SetupNumPublicConnections = 4,FString SetupMatchType = TEXT("FreeForAll")); void _DebugLog(FColor DisplayColor, const FString& DebugMessage); private: //将指针与按钮绑定起来,这里的绑定必须要指针变量名称和UMG的名称完全一样 UPROPERTY(meta=(BindWidget)) UButton* HostButton; UPROPERTY(meta=(BindWidget)) UButton* JoinButton; UFUNCTION() void HostButtonClicked(); UFUNCTION() void JoinButtonClincked(); UFUNCTION() void MenuTearDown(); class UMultiPlayerSessionSubsystem* MultiPlayerSessionSubsystem; int32 NumPublicConnections{4}; FString MatchType{TEXT("FreeForAll")}; };
.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "BaseMenu.h" #include "MultiPlayerSession/Public/MultiPlayerSessionSubsystem.h" #include "Components/Button.h" bool UBaseMenu::Initialize() { if(!Super::Initialize()) { return false; } if(HostButton) { HostButton->OnClicked.AddDynamic(this,&UBaseMenu::HostButtonClicked); } if(JoinButton) { JoinButton->OnClicked.AddDynamic(this,&UBaseMenu::JoinButtonClincked); } return true; } void UBaseMenu::NativeDestruct() { Super::NativeDestruct(); } void UBaseMenu::OnCreateSession(bool bWasSuccessful) { if(bWasSuccessful) { _DebugLog(FColor::Green,TEXT("CreateSession Successful")); } UWorld* World = GetWorld(); if(World) { World->ServerTravel("/Game/ThirdPerson/Maps/Lobby?listen"); } } void UBaseMenu::MenuSetup(int SetupNumPublicConnections ,FString SetupMatchType) { NumPublicConnections = SetupNumPublicConnections; MatchType = SetupMatchType; AddToViewport(); SetVisibility(ESlateVisibility::Visible); bIsFocusable = true; UWorld* World = GetWorld(); if(World) { APlayerController* PlayerController = World->GetFirstPlayerController(); if(PlayerController) { FInputModeUIOnly InputModeUIOnly; InputModeUIOnly.SetWidgetToFocus(TakeWidget()); InputModeUIOnly.SetLockMouseToViewportBehavior(EMouseLockMode::DoNotLock); PlayerController->SetInputMode(InputModeUIOnly); PlayerController->SetShowMouseCursor(true); } } UGameInstance* GameInstance = GetGameInstance(); if(GameInstance) { MultiPlayerSessionSubsystem = GameInstance->GetSubsystem<UMultiPlayerSessionSubsystem>(); } if(MultiPlayerSessionSubsystem) { MultiPlayerSessionSubsystem->MultiPlayerOnCreateSessionComplete.AddDynamic(this,&ThisClass::OnCreateSession); } } void UBaseMenu::_DebugLog(FColor DisplayColor, const FString& DebugMessage) { if(GEngine) { GEngine->AddOnScreenDebugMessage(-1,15.f,DisplayColor,DebugMessage); } } void UBaseMenu::HostButtonClicked() { if(MultiPlayerSessionSubsystem) { MultiPlayerSessionSubsystem->CreateSession(NumPublicConnections,MatchType); } _DebugLog(FColor::Blue,FString::Printf(TEXT("Create Session Success"))); } void UBaseMenu::JoinButtonClincked() { _DebugLog(FColor::Blue,FString::Printf(TEXT("Join Button Click"))); } void UBaseMenu::MenuTearDown() { UWorld* World = GetWorld(); RemoveFromParent(); APlayerController* PlayerController = World->GetFirstPlayerController(); FInputModeGameAndUI InputModeGameAndUI; PlayerController->SetInputMode(InputModeGameAndUI); PlayerController->SetShowMouseCursor(false); }
MultiplayerSessionSubsystem.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Subsystems/GameInstanceSubsystem.h" #include "Interfaces/OnlineSessionInterface.h" #include "MultiPlayerSessionSubsystem.generated.h" /** * 这里是我们自定义的委托 */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FMultiPlayerOnCreateSessionComplete ,bool, bWasSuccessful); UCLASS() class UMultiPlayerSessionSubsystem : public UGameInstanceSubsystem { GENERATED_BODY() public: UMultiPlayerSessionSubsystem(); /* * 这里是一个句柄,让菜单类可以访问Subsystem */ void CreateSession(int32 NumPublicConnections,FString MatchType); void FindSession(int32 MaxSearchResults); void JoinSession(const FOnlineSessionSearchResult& SessionResults); void DestroySession(); void StartSession(); /* * 这是给菜单类做的回调委托 */ FMultiPlayerOnCreateSessionComplete MultiPlayerOnCreateSessionComplete; protected: /* * 这里是委托 */ void CreateSessionComplete(FName SessionName, bool bWasSuccessful); void FindSessionsComplete(bool bWasSuccessful); void JoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result); void DestroySessionComplete(FName SessionName, bool bWasSuccessful); void StartSessionComplete(FName SessionName, bool bWasSuccessful); private: IOnlineSessionPtr OnlineSessionInterface; TSharedPtr<FOnlineSessionSettings> LastSessionSettings; /* * 添加OnlineSession委托到列表内 * 我们的游玩系统内部回调绑定到这里 * */ FOnCreateSessionCompleteDelegate CreateSessionCompleteDelegate; FDelegateHandle CreateSessionCompleteDelegate_Handle; FOnFindSessionsCompleteDelegate FindSessionsCompleteDelegate; FDelegateHandle FindSessionsCompleteDelegate_Handle; FOnJoinSessionCompleteDelegate JoinSessionCompleteDelegate; FDelegateHandle JoinSessionCompleteDelegate_Handle; FOnDestroySessionCompleteDelegate DestroySessionCompleteDelegate; FDelegateHandle DestroySessionCompleteDelegate_Handle; FOnStartSessionCompleteDelegate StartSessionCompleteDelegate; FDelegateHandle StartSessionCompleteDelegate_Handle; };
.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "MultiPlayerSessionSubsystem.h" #include "OnlineSessionSettings.h" #include "OnlineSubsystem.h" UMultiPlayerSessionSubsystem::UMultiPlayerSessionSubsystem(): CreateSessionCompleteDelegate(FOnCreateSessionCompleteDelegate::CreateUObject(this,&ThisClass::CreateSessionComplete)), FindSessionsCompleteDelegate(FOnFindSessionsCompleteDelegate::CreateUObject(this,&ThisClass::FindSessionsComplete)), JoinSessionCompleteDelegate(FOnJoinSessionCompleteDelegate::CreateUObject(this,&ThisClass::JoinSessionComplete)), DestroySessionCompleteDelegate(FOnDestroySessionCompleteDelegate::CreateUObject(this,&ThisClass::DestroySessionComplete)), StartSessionCompleteDelegate(FOnStartSessionCompleteDelegate::CreateUObject(this,&ThisClass::StartSessionComplete)) { IOnlineSubsystem* OnlineSubsystem = IOnlineSubsystem::Get(); if(OnlineSubsystem) { OnlineSessionInterface = OnlineSubsystem->GetSessionInterface(); } } void UMultiPlayerSessionSubsystem::CreateSession(int32 NumPublicConnections, FString MatchType) { if(!OnlineSessionInterface.IsValid()) { return; } auto ExistingSession = OnlineSessionInterface->GetNamedSession(NAME_GameSession); if(ExistingSession != nullptr) { OnlineSessionInterface->DestroySession(NAME_GameSession); } //存放创建委托 CreateSessionCompleteDelegate_Handle = OnlineSessionInterface->AddOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate); LastSessionSettings = MakeShareable(new FOnlineSessionSettings()); LastSessionSettings->bIsLANMatch = IOnlineSubsystem::Get()->GetSubsystemName() == "NULL" ? true:false; //最多4人 LastSessionSettings->NumPublicConnections =NumPublicConnections; //允许其他玩家加入 LastSessionSettings->bAllowJoinInProgress = true; //允许好友加入 LastSessionSettings->bAllowJoinViaPresence = true; //线上公开 LastSessionSettings->bShouldAdvertise = true; //显示用户状态 LastSessionSettings->bUsesPresence = true; //使用第三方平台 LastSessionSettings->bUseLobbiesIfAvailable = true; LastSessionSettings->Set(FName("MatchType"),MatchType,EOnlineDataAdvertisementType::ViaOnlineServiceAndPing); const ULocalPlayer* LocalPlayer = GetWorld()->GetFirstLocalPlayerFromController(); if(OnlineSessionInterface->CreateSession(*LocalPlayer->GetPreferredUniqueNetId(), NAME_GameSession , *LastSessionSettings)) { /*这里是创建失败*/ OnlineSessionInterface->ClearOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate_Handle); /*在这里广播*/ MultiPlayerOnCreateSessionComplete.Broadcast(false); } } void UMultiPlayerSessionSubsystem::FindSession(int32 MaxSearchResults) { } void UMultiPlayerSessionSubsystem::JoinSession(const FOnlineSessionSearchResult& SessionResults) { } void UMultiPlayerSessionSubsystem::DestroySession() { } void UMultiPlayerSessionSubsystem::StartSession() { } void UMultiPlayerSessionSubsystem::CreateSessionComplete(FName SessionName, bool bWasSuccessful) { /*当成功创建房间的时候,删除创建房间的句柄*/ if(OnlineSessionInterface) { OnlineSessionInterface->ClearOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate_Handle); } MultiPlayerOnCreateSessionComplete.Broadcast(bWasSuccessful); } void UMultiPlayerSessionSubsystem::FindSessionsComplete(bool bWasSuccessful) { } void UMultiPlayerSessionSubsystem::JoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result) { } void UMultiPlayerSessionSubsystem::DestroySessionComplete(FName SessionName, bool bWasSuccessful) { } void UMultiPlayerSessionSubsystem::StartSessionComplete(FName SessionName, bool bWasSuccessful) { }