当前位置:   article > 正文

UE4/5多人游戏详解(八、游戏模式和游戏状态里的函数重写,插件内地图的地址做变量,做变量让按钮出现不同状态,插件内的所有代码)

ue4/5多人游戏详解

目录

这里不写在插件里面,而是在游戏模式:

头文件:

Cpp文件:

更改ini文件

进入地图设置模式:

写插件里面,做一个变量:

写变量

然后更改函数MenuSet:

在子系统中做变量:

变量:

销毁的回调函数:

给按钮设置不输入

效果:

后续添加:

所有代码:

MultiPlayerSessionPlugin:

MultiPlayerSessionPlugin.h:

MultiPlayerSessionPlugin.cpp:

MultiPlayerSessionGISubsystem:

MultiPlayerSessionGISubsystem.h:

MultiPlayerSessionGISubsystem.cpp:

InPluginsMenu:

InPluginsMenu.h:

InPluginsMenu.cpp:

MultiPlayerSessionPlugin.Build.cs:

MultiPlayerSessionPlugin.uplugin:


游戏模式和游戏状态

GameMode和GameState在联网游戏中扮演着重要的角色,它们的函数可以帮助开发者管理游戏状态和玩家连接,实现联网游戏的功能。

这里不写在插件里面,而是在游戏模式:

创建这个类的原因是我们希望这个游戏模式是在Lobby这个地图使用的,而在这个Level(地图)中,每一次玩家加入和离开,我们都需要专用的函数去使用

 

这个创建到content里面,而不是写在插件里面的:

然后

头文件:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "GameFramework/GameModeBase.h"
  5. #include "LobbyGameMode.generated.h"
  6. /**
  7. *
  8. */
  9. UCLASS()
  10. class MOREPERSONTEST_API ALobbyGameMode : public AGameModeBase
  11. {
  12. GENERATED_BODY()
  13. public:
  14. //重写: 登录成功后调用。这是第一个可以安全地在PlayerController上调用复制函数的地方。
  15. virtual void PostLogin(APlayerController* NewPlayer)override;
  16. //重写: 当具有PlaverState的控制器离开游戏或被销毁时调用
  17. virtual void Logout(AController* Exiting)override;
  18. };

Cpp文件:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "LobbyGameMode.h"
  3. #include "GameFramework/GameStateBase.h"
  4. #include "GameFramework/PlayerState.h"
  5. #include "MorePersonTestCharacter.h"
  6. void ALobbyGameMode::PostLogin(APlayerController* NewPlayer)
  7. {
  8. //调用父类
  9. Super::PostLogin(NewPlayer);
  10. //GameState用于将游戏状态相关属性复制到所有客户端。
  11. if (GameState)
  12. {
  13. //获取玩家数量
  14. int32 NumberOfPlayer = GameState.Get()->PlayerArray.Num();
  15. if (GEngine)
  16. {
  17. GEngine->AddOnScreenDebugMessage(1, 15, FColor::Blue, FString::Printf(TEXT("Now PlayerNum is %d"), NumberOfPlayer));
  18. //获取状态->详情可以向父类看过去
  19. APlayerState* playerState =NewPlayer->GetPlayerState<APlayerState>();
  20. if (playerState)
  21. {
  22. //获取名字
  23. FString playerName =playerState->GetPlayerName();
  24. GEngine->AddOnScreenDebugMessage(-1, 15, FColor::Cyan, FString::Printf(TEXT("%s join game"), *playerName));
  25. }
  26. }
  27. }
  28. }
  29. void ALobbyGameMode::Logout(AController* Exiting)
  30. {
  31. //调用父类
  32. Super::Logout(Exiting);
  33. APlayerState* playerState = Exiting->GetPlayerState<APlayerState>();
  34. if (playerState)
  35. {
  36. //现在的人数
  37. int32 NumberOfPlayer = GameState.Get()->PlayerArray.Num();
  38. GEngine->AddOnScreenDebugMessage(1, 15, FColor::Blue, FString::Printf(TEXT("Now PlayerNum is %d"), NumberOfPlayer-1));
  39. //获取名字
  40. FString playerName = playerState->GetPlayerName();
  41. GEngine->AddOnScreenDebugMessage(-1, 15, FColor::Cyan, FString::Printf(TEXT("%s out the game"), *playerName));
  42. }
  43. }

更改ini文件

 

进入地图设置模式:

将游戏模式创建蓝图类,然后换蓝图的pawn上去,之后放到lobby的地图里面:

 

 

 

写插件里面,做一个变量:

写变量

我们之前进入这个Lobby的地图的时候,使用的是Lobby地图的地址

但这个是一个插件,那么,我们就需要考虑到不同项目有不同的地图,所以这里我们需要做一个全新的变量:

在菜单类中:

 

然后更改函数MenuSet

我们需要在MenuSet的后面添加这个地址:

 不用忘记更改cpp中的文件,然后添加这个:

 在完成这些之后,我们在下面的创建会话的回调函数就可以把绝对的地址引用改为这个变量:

 

在子系统中做变量:

变量:

 然后cpp里面

 实现销毁函数:

 代码:

  1. void UMultiPlayerSessionGISubsystem::DeleteSession()
  2. {
  3. if (!mySessionInterface.IsValid())
  4. {
  5. MultiPlayerOnDestroySessionComplete.Broadcast(false);
  6. return;
  7. }
  8. //句柄和添加委托
  9. DestroySessionCompleteDelegateHandle =mySessionInterface->AddOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegate);
  10. if (!mySessionInterface->DestroySession(NAME_GameSession))
  11. {
  12. //销毁会话失败
  13. mySessionInterface->ClearOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegateHandle);
  14. MultiPlayerOnDestroySessionComplete.Broadcast(false);
  15. }
  16. }

销毁的回调函数:

 代码:

  1. void UMultiPlayerSessionGISubsystem::onDestorySessionComplete(FName SessionName, bool bWasSuccessful)
  2. {
  3. if (mySessionInterface)
  4. {
  5. //清除
  6. mySessionInterface->ClearOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegateHandle);
  7. }
  8. //因为已经有一个会话了,所以要销毁会话然后在创建会话
  9. if (bWasSuccessful && bCreateSessionOnDestory)
  10. {
  11. //重置初始值
  12. bCreateSessionOnDestory = false;
  13. //创建会话
  14. CreateSession(LastNumPublicConnects,LastMatchType);
  15. }
  16. MultiPlayerOnDestroySessionComplete.Broadcast(bWasSuccessful);
  17. }

给按钮设置不输入

 给几个回调函数做一个判断

 

 

 

效果:

这样就会变得透明

 

后续添加:

到这里为止,想必懂的都懂了,所以我就直接进行一下后续的添加(因为这个是插件,所以):

 

这里的

UPROPERTY(BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))

的意思是允许在蓝图中私有访问

所有代码:

分别是3个头文件,3个cpp文件,1个uplugin文件和一个cs文件:

MultiPlayerSessionPlugin:

MultiPlayerSessionPlugin.h:

  1. // Copyright Epic Games, Inc. All Rights Reserved.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "Modules/ModuleManager.h"
  5. class FMultiPlayerSessionPluginModule : public IModuleInterface
  6. {
  7. public:
  8. /** IModuleInterface implementation */
  9. virtual void StartupModule() override;
  10. virtual void ShutdownModule() override;
  11. };
  12. //需要更改的ini设置:
  13. //更改:DefaultEngine.ini中的(添加到末尾):
  14. //[/ Script / Engine.GameEngine]
  15. //+ NetDriverDefinitions = (DefName = "GameNetDriver", DriverClassName = "OnlineSubsystemSteam.SteamNetDriver", DriverClassNameFallback = "OnlineSubsystemUtils.IpNetDriver")
  16. //
  17. //[OnlineSubsystem]
  18. //DefaultPlatformService = Steam
  19. //
  20. //[OnlineSubsystemSteam]
  21. //bEnabled = true
  22. //SteamDevAppId = 480
  23. //bInitServerOnClient = true
  24. //
  25. //[/ Script / OnlineSubsystemSteam.SteamNetDriver]
  26. //NetConnectionClassName = "OnlineSubsystemSteam.SteamNetConnection"
  27. //然后是DefaultGame.ini中的(添加到末尾):
  28. //[/ Script / Engine.GameSession]
  29. //MaxPlayers = 100

MultiPlayerSessionPlugin.cpp:

  1. // Copyright Epic Games, Inc. All Rights Reserved.
  2. #include "MultiPlayerSessionPlugin.h"
  3. #define LOCTEXT_NAMESPACE "FMultiPlayerSessionPluginModule"
  4. void FMultiPlayerSessionPluginModule::StartupModule()
  5. {
  6. // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
  7. }
  8. void FMultiPlayerSessionPluginModule::ShutdownModule()
  9. {
  10. // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
  11. // we call this function before unloading the module.
  12. }
  13. #undef LOCTEXT_NAMESPACE
  14. IMPLEMENT_MODULE(FMultiPlayerSessionPluginModule, MultiPlayerSessionPlugin)

MultiPlayerSessionGISubsystem:

MultiPlayerSessionGISubsystem.h:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "Subsystems/GameInstanceSubsystem.h"
  5. #include "Interfaces/OnlineSessionInterface.h"
  6. #include "MultiPlayerSessionGISubsystem.generated.h"
  7. //自定义委托,用于回调到菜单类
  8. //动态多播
  9. DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FMultiOnCreateSessionComplete, bool, bWasSuccessful);
  10. //这里使用多播,而不是动态多播
  11. DECLARE_MULTICAST_DELEGATE_TwoParams(FMultiOnFindSessionComplete, const TArray<FOnlineSessionSearchResult>& SessionResult, bool bWasSuccessful);
  12. DECLARE_MULTICAST_DELEGATE_OneParam(FMultiOnJoinSessionComplete, EOnJoinSessionCompleteResult::Type Result);
  13. //动态多播
  14. DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FMultiOnDestroySessionComplete, bool, bWasSuccessful);
  15. DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FMultiOnStartSessionComplete, bool, bWasSuccessful);
  16. /**
  17. *
  18. */
  19. UCLASS()
  20. class MULTIPLAYERSESSIONPLUGIN_API UMultiPlayerSessionGISubsystem : public UGameInstanceSubsystem
  21. {
  22. GENERATED_BODY()
  23. public:
  24. UMultiPlayerSessionGISubsystem();
  25. //
  26. //会话 --公开的链接函数
  27. //这里将输入玩家数量和会话的类型(用于匹配不同的会话)
  28. void CreateSession(int32 playerConnectNum, FString MatchType);
  29. //输入的是寻找会话的最大数量
  30. void FindSession(int32 findSessionMaxNum);
  31. //加入会话
  32. void JoinSession(const FOnlineSessionSearchResult& SessionResult);
  33. //删除
  34. void DeleteSession();
  35. //开始
  36. void StartSession();
  37. //将回调函数绑定到的菜单类的自定义委托
  38. //委托变量
  39. //UPROPERTY(BlueprintAssignable)
  40. FMultiOnCreateSessionComplete MultiPlayerOnCreateSessionComplete;
  41. FMultiOnFindSessionComplete MultiPlayerOnFindSessionComplete;
  42. FMultiOnJoinSessionComplete MultiPlayerOnJoinSessionComplete;
  43. FMultiOnDestroySessionComplete MultiPlayerOnDestroySessionComplete;
  44. FMultiOnStartSessionComplete MultiPlayerOnStartSessionComplete;
  45. protected:
  46. //回调函数,将会绑定到委托(根据委托输入对应输入对象)
  47. void onCreateSessionComplete(FName SessionName, bool bWasSuccessful);
  48. void onFindSessionComplete(bool bWasSuccessful);
  49. void onJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result);
  50. void onDestorySessionComplete(FName SessionName, bool bWasSuccessful);
  51. void onStartSessionComplete(FName SessionName, bool bWasSuccessful);
  52. private:
  53. //会话接口
  54. IOnlineSessionPtr mySessionInterface;
  55. //会话设置的智能指针 查看上次的会话设置
  56. TSharedPtr<FOnlineSessionSettings> LastSessionSettings;
  57. //寻找会话的智能指针
  58. TSharedPtr<FOnlineSessionSearch> LastSessionSearch;
  59. //需要添加的委托,到时候要一一对应制作回调函数
  60. FOnCreateSessionCompleteDelegate CreateSessionCompleteDelegate;
  61. FDelegateHandle CreateSessionCompleteDelegateHandle;//委托句柄
  62. FOnFindSessionsCompleteDelegate FindSessionsCompleteDelegate;
  63. FDelegateHandle FindSessionsCompleteDelegateHandle;//委托句柄
  64. FOnJoinSessionCompleteDelegate JoinSessionCompleteDelegate;
  65. FDelegateHandle JoinSessionCompleteDelegateHandle;//委托句柄
  66. FOnDestroySessionCompleteDelegate DestroySessionCompleteDelegate;
  67. FDelegateHandle DestroySessionCompleteDelegateHandle;//委托句柄
  68. FOnStartSessionCompleteDelegate StartSessionCompleteDelegate;
  69. FDelegateHandle StartSessionCompleteDelegateHandle;//委托句柄
  70. //用于判断是否是在创建会话的时候正在销毁会话
  71. bool bCreateSessionOnDestory{ false };
  72. int32 LastNumPublicConnects;
  73. FString LastMatchType;
  74. };

MultiPlayerSessionGISubsystem.cpp:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "MultiPlayerSessionGISubsystem.h"
  3. #include "OnlineSubsystem.h"
  4. #include "OnlineSessionSettings.h"
  5. UMultiPlayerSessionGISubsystem::UMultiPlayerSessionGISubsystem():
  6. CreateSessionCompleteDelegate(FOnCreateSessionCompleteDelegate::CreateUObject(this,&UMultiPlayerSessionGISubsystem::onCreateSessionComplete)),
  7. FindSessionsCompleteDelegate(FOnFindSessionsCompleteDelegate::CreateUObject(this,&UMultiPlayerSessionGISubsystem::onFindSessionComplete)),
  8. JoinSessionCompleteDelegate(FOnJoinSessionCompleteDelegate::CreateUObject(this,&UMultiPlayerSessionGISubsystem::onJoinSessionComplete)),
  9. DestroySessionCompleteDelegate(FOnDestroySessionCompleteDelegate::CreateUObject(this,&UMultiPlayerSessionGISubsystem::onDestorySessionComplete)),
  10. StartSessionCompleteDelegate(FOnStartSessionCompleteDelegate::CreateUObject(this,&UMultiPlayerSessionGISubsystem::onStartSessionComplete))
  11. {
  12. //获取子系统
  13. IOnlineSubsystem* Subsystem = IOnlineSubsystem::Get();
  14. if (Subsystem)
  15. {
  16. //从子系统中获取了会话系统,并放到我们的会话接口指针里面
  17. mySessionInterface = Subsystem->GetSessionInterface();
  18. }
  19. }
  20. void UMultiPlayerSessionGISubsystem::CreateSession(int32 playerConnectNum, FString MatchType)
  21. {
  22. //判断会话系统是否有效
  23. if (!mySessionInterface.IsValid())
  24. {
  25. return;
  26. }
  27. //有会话则获取现有的会话
  28. auto ExistingSession = mySessionInterface->GetNamedSession(NAME_GameSession);
  29. //如果现有的会话并不是空的
  30. if (ExistingSession != nullptr)
  31. {
  32. bCreateSessionOnDestory = true;
  33. LastNumPublicConnects = playerConnectNum;
  34. LastMatchType = MatchType;
  35. //删除游戏会话
  36. DeleteSession();
  37. }
  38. //在会话创建请求完成时触发委托CreateSessionCompleteDelegate,返回句柄到CreateSessionCompleteDelegateHandle,方便之后删除
  39. CreateSessionCompleteDelegateHandle = mySessionInterface->AddOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate);
  40. //
  41. LastSessionSettings = MakeShareable(new FOnlineSessionSettings());
  42. //判断现在的接口是不是空的,是则返回true,不是则返回false【此游戏将仅限局域网,外部玩家无法看到,是true还是false】
  43. //直接在这里判断你是局域网还不是
  44. LastSessionSettings->bIsLANMatch = IOnlineSubsystem::Get()->GetSubsystemName()=="NULL"?true:false;
  45. //可用的连接数量是多少
  46. LastSessionSettings->NumPublicConnections = playerConnectNum;
  47. //是否允许加入线程
  48. LastSessionSettings->bAllowJoinInProgress = true;
  49. //是否允许通过玩家存在加入
  50. LastSessionSettings->bAllowJoinViaPresence = true;
  51. //该比赛是否在在线服务上面公开广告
  52. LastSessionSettings->bShouldAdvertise = true;
  53. //是否显示用户状态信息
  54. LastSessionSettings->bUsesPresence = true;
  55. //不同key和value的匹配,从现有会话设置中定义会话设置
  56. LastSessionSettings->Set(FName("MatchType"), MatchType, EOnlineDataAdvertisementType::ViaOnlineServiceAndPing);
  57. //用于防止不同的构建在搜索期间看到彼此
  58. LastSessionSettings->BuildUniqueId = 1;
  59. //支持api则使用
  60. LastSessionSettings->bUseLobbiesIfAvailable = true;
  61. //获取本地的第一个玩家控制器
  62. const ULocalPlayer* localPlayer = GetWorld()->GetFirstLocalPlayerFromController();
  63. //*localPlayer->GetPreferredUniqueNetId() 首选唯一网格ID
  64. //判断创建会话是否成功
  65. if (!mySessionInterface->CreateSession(*localPlayer->GetPreferredUniqueNetId(), NAME_GameSession, *LastSessionSettings))
  66. {
  67. //创建失败
  68. //委托列表中删除委托,传入的是一个句柄(这个CreateSessionCompleteDelegateHandle在上面获取过)
  69. mySessionInterface->ClearOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegateHandle);
  70. //广播自定义委托:传给所有注册的回调函数false
  71. MultiPlayerOnCreateSessionComplete.Broadcast(false);
  72. }
  73. }
  74. void UMultiPlayerSessionGISubsystem::FindSession(int32 findSessionMaxNum)
  75. {
  76. if (!mySessionInterface.IsValid())
  77. {
  78. return;
  79. }
  80. //会话接口委托列表添加委托,然后句柄获取
  81. FindSessionsCompleteDelegateHandle = mySessionInterface->AddOnFindSessionsCompleteDelegate_Handle(FindSessionsCompleteDelegate);
  82. LastSessionSearch = MakeShareable(new FOnlineSessionSearch);
  83. //配对服务返回的查询的最大数目
  84. LastSessionSearch->MaxSearchResults = findSessionMaxNum;
  85. //查询是否用于局域网匹配
  86. LastSessionSearch->bIsLanQuery = IOnlineSubsystem::Get()->GetSubsystemName() == "NULL" ? true : false;
  87. //SEARCH_PRESENCE :仅搜索存在会话(值为true/false)
  88. //QuerySettings :用于查找匹配服务器的查询
  89. LastSessionSearch->QuerySettings.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals);
  90. //获取本地的玩家控制器
  91. const ULocalPlayer* playerControler = GetWorld()->GetFirstLocalPlayerFromController();
  92. //搜索与指定匹配的对话
  93. //GetPreferredUniqueNetId :检索首选的唯一网id。这是为了向后兼容不使用缓存唯一网络id逻辑的游戏
  94. if (!mySessionInterface->FindSessions(*playerControler->GetPreferredUniqueNetId(), LastSessionSearch.ToSharedRef()))
  95. {
  96. //寻找失败
  97. //清除
  98. mySessionInterface->ClearOnFindSessionsCompleteDelegate_Handle(FindSessionsCompleteDelegateHandle);
  99. //因为失败了,所以传入的是一个空的数组和false
  100. MultiPlayerOnFindSessionComplete.Broadcast(TArray<FOnlineSessionSearchResult>(), false);
  101. }
  102. }
  103. void UMultiPlayerSessionGISubsystem::JoinSession(const FOnlineSessionSearchResult& SessionResult)
  104. {
  105. if (!mySessionInterface.IsValid())
  106. {
  107. //无效情况下
  108. //广播到所有绑定对象:UnknownError
  109. MultiPlayerOnJoinSessionComplete.Broadcast(EOnJoinSessionCompleteResult::UnknownError);
  110. return;
  111. }
  112. //获取句柄和委托列表添加
  113. JoinSessionCompleteDelegateHandle =mySessionInterface->AddOnJoinSessionCompleteDelegate_Handle(JoinSessionCompleteDelegate);
  114. //加入会话
  115. const ULocalPlayer* localPlayer = GetWorld()->GetFirstLocalPlayerFromController();
  116. if (!mySessionInterface->JoinSession(*localPlayer->GetPreferredUniqueNetId(), NAME_GameSession, SessionResult))
  117. {
  118. //加入失败
  119. //清除委托
  120. mySessionInterface->ClearOnJoinSessionCompleteDelegate_Handle(JoinSessionCompleteDelegateHandle);
  121. //广播回调函数为未知错误
  122. MultiPlayerOnJoinSessionComplete.Broadcast(EOnJoinSessionCompleteResult::UnknownError);
  123. }
  124. }
  125. void UMultiPlayerSessionGISubsystem::DeleteSession()
  126. {
  127. if (!mySessionInterface.IsValid())
  128. {
  129. MultiPlayerOnDestroySessionComplete.Broadcast(false);
  130. return;
  131. }
  132. //句柄和添加委托
  133. DestroySessionCompleteDelegateHandle =mySessionInterface->AddOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegate);
  134. if (!mySessionInterface->DestroySession(NAME_GameSession))
  135. {
  136. //销毁会话失败
  137. mySessionInterface->ClearOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegateHandle);
  138. MultiPlayerOnDestroySessionComplete.Broadcast(false);
  139. }
  140. }
  141. void UMultiPlayerSessionGISubsystem::StartSession()
  142. {
  143. }
  144. void UMultiPlayerSessionGISubsystem::onCreateSessionComplete(FName SessionName, bool bWasSuccessful)
  145. {
  146. if (mySessionInterface)
  147. {
  148. //这里是清除之前注册的回调函数,以便在下一次创建会话时不会重复调用(即委托句柄)
  149. mySessionInterface->ClearOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegateHandle);
  150. }
  151. //传给所有注册的回调函数 bWasSuccessful
  152. MultiPlayerOnCreateSessionComplete.Broadcast(bWasSuccessful);
  153. }
  154. void UMultiPlayerSessionGISubsystem::onFindSessionComplete(bool bWasSuccessful)
  155. {
  156. if (mySessionInterface)
  157. {
  158. //清除
  159. mySessionInterface->ClearOnFindSessionsCompleteDelegate_Handle(FindSessionsCompleteDelegateHandle);
  160. }
  161. //查找的会话数量
  162. if (LastSessionSearch->SearchResults.Num()<=0)
  163. {
  164. //因为失败了,所以传入的是一个空的数组和false
  165. MultiPlayerOnFindSessionComplete.Broadcast(TArray<FOnlineSessionSearchResult>(), false);
  166. return;
  167. }
  168. //传入菜单
  169. MultiPlayerOnFindSessionComplete.Broadcast(LastSessionSearch->SearchResults, bWasSuccessful);
  170. }
  171. void UMultiPlayerSessionGISubsystem::onJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
  172. {
  173. if (mySessionInterface)
  174. {
  175. //执行完成,所以清除一下
  176. mySessionInterface->ClearOnJoinSessionCompleteDelegate_Handle(JoinSessionCompleteDelegateHandle);
  177. }
  178. //广播到菜单的onjoinsession
  179. MultiPlayerOnJoinSessionComplete.Broadcast(Result);
  180. }
  181. void UMultiPlayerSessionGISubsystem::onDestorySessionComplete(FName SessionName, bool bWasSuccessful)
  182. {
  183. if (mySessionInterface)
  184. {
  185. //清除
  186. mySessionInterface->ClearOnDestroySessionCompleteDelegate_Handle(DestroySessionCompleteDelegateHandle);
  187. }
  188. //因为已经有一个会话了,所以要销毁会话然后在创建会话
  189. if (bWasSuccessful && bCreateSessionOnDestory)
  190. {
  191. //重置初始值
  192. bCreateSessionOnDestory = false;
  193. //创建会话
  194. CreateSession(LastNumPublicConnects,LastMatchType);
  195. }
  196. MultiPlayerOnDestroySessionComplete.Broadcast(bWasSuccessful);
  197. }
  198. void UMultiPlayerSessionGISubsystem::onStartSessionComplete(FName SessionName, bool bWasSuccessful)
  199. {
  200. }

InPluginsMenu:

InPluginsMenu.h:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include "Blueprint/UserWidget.h"
  5. #include "Interfaces/OnlineSessionInterface.h"
  6. #include "InPluginsMenu.generated.h"
  7. /**
  8. *
  9. */
  10. UCLASS()
  11. class MULTIPLAYERSESSIONPLUGIN_API UInPluginsMenu : public UUserWidget
  12. {
  13. GENERATED_BODY()
  14. public:
  15. //菜单设置
  16. UFUNCTION(BlueprintCallable)
  17. void MenuSet(int32 NumberPublicConnect =4, FString TypeOfMatch= FString(TEXT("FreeForAll")),FString LobbyPath =FString(TEXT("/Game/Map/Lobby")));
  18. protected:
  19. virtual bool Initialize() override;
  20. //这是5.0的重载
  21. //如果是5.1无法使用的,请使用virtual void NativeDestruct() override
  22. //【我专门在5.1测试了一遍,找不到OnLevelRemovedFromWorld】;
  23. virtual void OnLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld) override;
  24. //子系统上的自定义委托的回调 如果绑定失败则加上UFUNCTION
  25. UFUNCTION()
  26. void onCreateSession(bool bWasSuccessful);
  27. void onFindSession(const TArray<FOnlineSessionSearchResult>& SessionResult, bool bWasSuccessful);
  28. void onJoinSession(EOnJoinSessionCompleteResult::Type Result);
  29. UFUNCTION()
  30. void onDestroySession(bool bWasSuccessful);
  31. UFUNCTION()
  32. void onStartSession(bool bWasSuccessful);
  33. private:
  34. //两个按钮,会和蓝图中的按钮链接,所以蓝图中的按钮要和c++中的一样名字
  35. UPROPERTY(meta=(BindWidget))
  36. class UButton* CreateSessionBotton;
  37. UPROPERTY(meta = (BindWidget))
  38. UButton* JoinSessionBotton;
  39. //点击创建会话按钮事件
  40. UFUNCTION()
  41. void CreateBottonClicked();
  42. //点击加入会话按钮事件
  43. UFUNCTION()
  44. void JoinBottonClicked();
  45. //移除控件
  46. void MenuTearDown();
  47. //这是最开始创建的类,在这里做一个变量
  48. //用于处理所有在线会话的子系统
  49. class UMultiPlayerSessionGISubsystem* MultiPlayerSessionSubsystem;
  50. private:
  51. //初始化默认为4
  52. UPROPERTY(BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))
  53. int32 NumPublicConnect{4};
  54. //value值
  55. UPROPERTY(BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))
  56. FString MatchType{ TEXT("FreeForAll") };
  57. //大厅地址 初始化的空值
  58. FString pathToLobby{ TEXT("") };
  59. };

InPluginsMenu.cpp:

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "InPluginsMenu.h"
  3. #include "Components/Button.h"
  4. #include "MultiPlayerSessionGISubsystem.h"
  5. #include "OnlineSessionSettings.h"
  6. #include "Interfaces/OnlineSessionInterface.h"
  7. #include "OnlineSubsystem.h"
  8. void UInPluginsMenu::MenuSet(int32 NumberPublicConnect, FString TypeOfMatch, FString LobbyPath)
  9. {
  10. //获取地址
  11. pathToLobby = FString::Printf(TEXT("%s?listen"), *LobbyPath);
  12. //私有变量初始化
  13. NumPublicConnect = NumberPublicConnect;
  14. MatchType = TypeOfMatch;
  15. //添加到视口
  16. AddToViewport();
  17. //设置可视
  18. SetVisibility(ESlateVisibility::Visible);
  19. //bIsFocusable设置为true是允许点击的时候受到焦点,是UserWidget里面定义的
  20. bIsFocusable = true;
  21. UWorld* world = GetWorld();
  22. if (world)
  23. {
  24. APlayerController* playerControler = world->GetFirstPlayerController();
  25. if (playerControler)
  26. {
  27. //FInputModeUIOnly 用于设置只允许ui响应用户输入的输入模式的数据结构
  28. FInputModeUIOnly inputModeData;
  29. //SetWidgetToFocus设置焦距
  30. //TakeWidget()获取底层的slate部件,不存在则构造它
  31. inputModeData.SetWidgetToFocus(TakeWidget());
  32. //设置鼠标在视口的行为,这里是不锁定
  33. inputModeData.SetLockMouseToViewportBehavior(EMouseLockMode::DoNotLock);
  34. //设置完毕输入模式的东西之后,在玩家控制器里面将设置好的输入模式设置到玩家控制器的输入模式
  35. playerControler->SetInputMode(inputModeData);
  36. //显示鼠标光标
  37. playerControler->SetShowMouseCursor(true);
  38. }
  39. }
  40. //获取现在的游戏实例判断是否存在
  41. UGameInstance* gameInstance = GetGameInstance();
  42. if (gameInstance)
  43. {
  44. MultiPlayerSessionSubsystem =gameInstance->GetSubsystem<UMultiPlayerSessionGISubsystem>();
  45. }
  46. if (MultiPlayerSessionSubsystem)
  47. {
  48. //添加动态委托 回调函数onCreateSession
  49. MultiPlayerSessionSubsystem->MultiPlayerOnCreateSessionComplete.AddDynamic(this, &ThisClass::onCreateSession);
  50. MultiPlayerSessionSubsystem->MultiPlayerOnFindSessionComplete.AddUObject(this, &ThisClass::onFindSession);
  51. MultiPlayerSessionSubsystem->MultiPlayerOnJoinSessionComplete.AddUObject(this, &ThisClass::onJoinSession);
  52. MultiPlayerSessionSubsystem->MultiPlayerOnDestroySessionComplete.AddDynamic(this, &ThisClass::onDestroySession);
  53. MultiPlayerSessionSubsystem->MultiPlayerOnStartSessionComplete.AddDynamic(this, &ThisClass::onStartSession);
  54. }
  55. }
  56. bool UInPluginsMenu::Initialize()
  57. {
  58. if (!Super::Initialize())
  59. {
  60. return false;
  61. }
  62. if (CreateSessionBotton)
  63. {
  64. //动态绑定
  65. CreateSessionBotton->OnClicked.AddDynamic(this,&UInPluginsMenu::CreateBottonClicked);
  66. }
  67. if (JoinSessionBotton)
  68. {
  69. //动态绑定
  70. JoinSessionBotton->OnClicked.AddDynamic(this, &UInPluginsMenu::JoinBottonClicked);
  71. }
  72. return true;
  73. }
  74. void UInPluginsMenu::OnLevelRemovedFromWorld(ULevel* InLevel, UWorld* InWorld)
  75. {
  76. //这样就删除了控件和重置了输入模式和光标
  77. MenuTearDown();
  78. //执行父类
  79. Super::OnLevelRemovedFromWorld(InLevel,InWorld);
  80. }
  81. void UInPluginsMenu::onCreateSession(bool bWasSuccessful)
  82. {
  83. if (bWasSuccessful)
  84. {
  85. if (GEngine)
  86. {
  87. GEngine->AddOnScreenDebugMessage(-1, 15, FColor::Blue, FString(TEXT("create success")));
  88. }
  89. UWorld* world = GetWorld();
  90. if (world)
  91. {
  92. //将服务器跳转到新关卡
  93. world->ServerTravel(pathToLobby);
  94. }
  95. }
  96. else
  97. {
  98. if (GEngine)
  99. {
  100. GEngine->AddOnScreenDebugMessage(-1, 15, FColor::Red, FString(TEXT("create Failed")));
  101. }
  102. //设置按钮的当前启用状态
  103. CreateSessionBotton->SetIsEnabled(true);
  104. }
  105. }
  106. void UInPluginsMenu::onFindSession(const TArray<FOnlineSessionSearchResult>& SessionResult, bool bWasSuccessful)
  107. {
  108. if (MultiPlayerSessionSubsystem == nullptr)
  109. {
  110. return;
  111. }
  112. //遍历找到的会话数组
  113. for (auto Result : SessionResult)
  114. {
  115. FString SettingsValue;
  116. //获取定义会话设置的key对应的value赋予SettingsValue
  117. Result.Session.SessionSettings.Get(FName(TEXT("MatchType")), SettingsValue);
  118. if (SettingsValue ==MatchType)//判断SettingsValue和MatchType是否一致,即找到了会话
  119. {
  120. //加入会话(在这里)
  121. MultiPlayerSessionSubsystem->JoinSession(Result);
  122. return;
  123. }
  124. }
  125. //如果失败了,或者知道的会话数量为0
  126. if (!bWasSuccessful ||SessionResult.Num()==0)
  127. {
  128. JoinSessionBotton->SetIsEnabled(true);
  129. }
  130. }
  131. void UInPluginsMenu::onJoinSession(EOnJoinSessionCompleteResult::Type Result)
  132. {
  133. IOnlineSubsystem* onlineSubsystem = IOnlineSubsystem::Get();
  134. if (onlineSubsystem)
  135. {
  136. //临时接口
  137. IOnlineSessionPtr TempMySessionInterface = onlineSubsystem->GetSessionInterface();
  138. if (TempMySessionInterface.IsValid())
  139. {
  140. //给予tempAddress地址
  141. FString tempAddress;
  142. TempMySessionInterface->GetResolvedConnectString(NAME_GameSession,tempAddress);
  143. //从游戏实例里面获取本地的第一个玩家控制器
  144. APlayerController* playerControler = GetGameInstance()->GetFirstLocalPlayerController();
  145. if (playerControler)
  146. {
  147. //世界跳跃
  148. //旅行到不同的地图或IP地址。
  149. //在执行任何操作之前调用PreClientTravel事件。
  150. playerControler->ClientTravel(tempAddress, ETravelType::TRAVEL_Absolute);
  151. }
  152. }
  153. }
  154. //如果不是成功
  155. if (Result !=EOnJoinSessionCompleteResult::Success)
  156. {
  157. JoinSessionBotton->SetIsEnabled(true);
  158. }
  159. }
  160. void UInPluginsMenu::onDestroySession(bool bWasSuccessful)
  161. {
  162. }
  163. void UInPluginsMenu::onStartSession(bool bWasSuccessful)
  164. {
  165. }
  166. void UInPluginsMenu::CreateBottonClicked()
  167. {
  168. //设置按钮的当前启用状态
  169. CreateSessionBotton->SetIsEnabled(false);
  170. if (MultiPlayerSessionSubsystem)
  171. {
  172. //创建会话
  173. MultiPlayerSessionSubsystem->CreateSession(NumPublicConnect,MatchType);
  174. }
  175. }
  176. void UInPluginsMenu::JoinBottonClicked()
  177. {
  178. //设置按钮的当前启用状态
  179. JoinSessionBotton->SetIsEnabled(false);
  180. if (MultiPlayerSessionSubsystem)
  181. {
  182. //寻找会话
  183. MultiPlayerSessionSubsystem->FindSession(10000);
  184. }
  185. }
  186. void UInPluginsMenu::MenuTearDown()
  187. {
  188. //从父项中移除
  189. RemoveFromParent();
  190. UWorld* world = GetWorld();
  191. if (world)
  192. {
  193. //获取玩家控制器
  194. APlayerController* playerControler = world->GetFirstPlayerController();
  195. if (playerControler)
  196. {
  197. //创建默认的输入模式,然后设置为控制器
  198. FInputModeGameOnly inputModeData;
  199. playerControler->SetInputMode(inputModeData);
  200. //鼠标光标设置
  201. playerControler->SetShowMouseCursor(false);
  202. }
  203. }
  204. }

MultiPlayerSessionPlugin.Build.cs:

  1. // Copyright Epic Games, Inc. All Rights Reserved.
  2. using UnrealBuildTool;
  3. public class MultiPlayerSessionPlugin : ModuleRules
  4. {
  5. public MultiPlayerSessionPlugin(ReadOnlyTargetRules Target) : base(Target)
  6. {
  7. PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
  8. PublicIncludePaths.AddRange(
  9. new string[] {
  10. // ... add public include paths required here ...
  11. }
  12. );
  13. PrivateIncludePaths.AddRange(
  14. new string[] {
  15. // ... add other private include paths required here ...
  16. }
  17. );
  18. PublicDependencyModuleNames.AddRange(
  19. new string[]
  20. {
  21. "Core",
  22. "OnlineSubsystem",
  23. "OnlineSubsystemSteam",
  24. "UMG",
  25. "Slate",
  26. "SlateCore",
  27. // ... add other public dependencies that you statically link with here ...
  28. }
  29. );
  30. PrivateDependencyModuleNames.AddRange(
  31. new string[]
  32. {
  33. "CoreUObject",
  34. "Engine",
  35. "Slate",
  36. "SlateCore",
  37. // ... add private dependencies that you statically link with here ...
  38. }
  39. );
  40. DynamicallyLoadedModuleNames.AddRange(
  41. new string[]
  42. {
  43. // ... add any modules that your module loads dynamically here ...
  44. }
  45. );
  46. }
  47. }

MultiPlayerSessionPlugin.uplugin:

  1. {
  2. "FileVersion": 3,
  3. "Version": 1,
  4. "VersionName": "1.0",
  5. "FriendlyName": "MultiPlayerSessionPlugin",
  6. "Description": "a multiplayer game use,join and connect in steam session",
  7. "Category": "Other",
  8. "CreatedBy": "LinJohn",
  9. "CreatedByURL": "",
  10. "DocsURL": "",
  11. "MarketplaceURL": "",
  12. "SupportURL": "",
  13. "CanContainContent": true,
  14. "IsBetaVersion": false,
  15. "IsExperimentalVersion": false,
  16. "Installed": false,
  17. "Modules": [
  18. {
  19. "Name": "MultiPlayerSessionPlugin",
  20. "Type": "Runtime",
  21. "LoadingPhase": "Default"
  22. }
  23. ],
  24. "Plugins": [
  25. {
  26. "Name": "OnlineSubsystem",
  27. "Enabled": true
  28. },
  29. {
  30. "Name": "OnlineSubsystemSteam",
  31. "Enabled": true
  32. }
  33. ]
  34. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/91414
推荐阅读
相关标签
  

闽ICP备14008679号