PUN 2 菜鸟养成记 3进入游戏
緊接上篇?菜鳥養成記 2主服務? ? ?https://blog.csdn.net/u010294054/article/details/88077896
讓我們趕快進入游戲的海洋吧
第一步 主機調用加載游戲場景? 嗯? 為啥只有主機調用加載場景?
PhotonNetwork.LoadLevel("DemoAsteroids-GameScene");因為我們在一開始就設置了自動同步場景
PhotonNetwork.AutomaticallySyncScene = true;主機調用PhotonNetwork.LoadLevel() 后,其他客戶端都會收到切換場景的消息并在這里處理
public static partial class PhotonNetwork {public static void LoadLevel(int levelNumber){if (PhotonNetwork.AutomaticallySyncScene){SetLevelInPropsIfSynced(levelNumber);}PhotonNetwork.IsMessageQueueRunning = false;loadingLevelAndPausedNetwork = true;_AsyncLevelLoadingOperation = SceneManager.LoadSceneAsync(levelNumber,LoadSceneMode.Single);} }愛找茬的小伙伴這時候就會發現問題了:
這個切換場景的方法和主機通知其他客戶端切換場景的方法是一個方法
而且PhotonNetwork.AutomaticallySyncScene 也是 == true
這里會不會出現互相通知加載場景的死循環呢?
吭吭 這位小伙伴 大可放心 ,別人不會這么蠢的, SetLevelInPropsIfSynced 方法的第一行就判斷了 非主機就直接return
internal static void SetLevelInPropsIfSynced(object levelId) {if (!PhotonNetwork.AutomaticallySyncScene || !PhotonNetwork.IsMasterClient || PhotonNetwork.CurrentRoom == null){return;} }主機已經切換好了場景了 現在要等待其他客戶端進入游戲
private bool CheckAllPlayerLoadedLevel() {foreach (Player p in PhotonNetwork.PlayerList){object playerLoadedLevel;if (p.CustomProperties.TryGetValue(AsteroidsGame.PLAYER_LOADED_LEVEL, out playerLoadedLevel)){if ((bool) playerLoadedLevel){continue;}}return false;}return true; }其他客戶端都進入場景之后通知 開始 進入游戲倒計時
Hashtable props = new Hashtable {{CountdownTimer.CountdownStartTime, (float) PhotonNetwork.Time} }; PhotonNetwork.CurrentRoom.SetCustomProperties(props);?
不墨跡了,我們快開始游戲吧!
開始游戲的第一件事 就是加載我們的雷霆戰機
ennnn...不要太在意這個模型 我們來看一下如何同步加載物體
PhotonNetwork.Instantiate("Spaceship", Vector3.zero ,Quaternion.Euler(Vector3.zero), 0);我們來模仿一下 試試加載一個自己創建的球體
在Resources文件夾下面創建一個名字為Sphere的預制體
我們來試試看
PhotonNetwork.Instantiate("Sphere", Vector3.zero ,Quaternion.Euler(Vector3.zero), 0);報錯了...
PhotonNetwork.Instantiate() can only instantiate objects with a PhotonView component. This prefab does not have one: Sphere
PUN同步加載的物體不能缺少這個組件,我們需要添加 PhotonView到這個預制體上
再運行一遍 ,恭喜你 現在能成功同步加載物體了!
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的PUN 2 菜鸟养成记 3进入游戏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: excel文件运行报错(xx.xlsx)
- 下一篇: [经典]PK:星际争霸 vs 魔兽争霸3