Created
January 25, 2018 12:19
-
-
Save nickyeh97/578975b5eb70bdc17a8fe2681f79a584 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.SceneManagement; | |
using UnityEngine.UI; | |
public class PhotonManager : Photon.PunBehaviour | |
{ | |
public static PhotonManager instance; | |
//客户端版本 | |
public string _gameVersion = "ver1.2"; | |
// 本機玩家 | |
public static GameObject localPlayer; | |
//大廳玩家 | |
public static GameObject lobbyPlayer; | |
//遊戲房間玩家 | |
public PhotonPlayer[] players; | |
//房间列表 | |
public RectTransform RoomListPanel; | |
//玩家列表 | |
public RectTransform GameRoomPanel; | |
//Team | |
public RectTransform TeamA; | |
public RectTransform TeamB; | |
//UI | |
public GameObject lobbyPanel; | |
public GameObject NameBox; | |
public InputField UserNameField; | |
public Text UserName; | |
public GameObject CreateBtn; | |
public GameObject HomeBtn; | |
public GameObject StartBtn; | |
private void Awake()//載入場景 | |
{ | |
if (instance != null) | |
{ | |
DestroyImmediate(gameObject); | |
return; | |
} | |
DontDestroyOnLoad(gameObject); | |
DontDestroyOnLoad(lobbyPanel); | |
instance = this; | |
// 讓 PUN 能自動同步載入場景, 可以避免在載入場景初始化時發生一些網路問題. | |
//这里保证所有主机上调用 PhotonNetwork.LoadLevel() 的时候主机和客户端能同时进入新的场景 | |
PhotonNetwork.automaticallySyncScene = true; | |
} | |
private void Start()//連上Photon Cloud | |
{ | |
//UserName | |
SetPlayerName(); | |
//將PUN連上Photon Cloud | |
PhotonNetwork.ConnectUsingSettings("BattleGround_" + _gameVersion); | |
GameRoomPanel.gameObject.SetActive(false); | |
HomeBtn.SetActive(false); | |
StartBtn.SetActive(false); | |
} | |
/// <summary> | |
/// 連接大廳失败 | |
/// </summary> | |
/// <param name="error"></param> | |
private void OnFailedToConnect(NetworkConnectionError error) | |
{ | |
Debug.Log("fail to Connect"); | |
} | |
private void SetPlayerName() | |
{ | |
PhotonNetwork.player.NickName = PlayerPrefs.GetString("Username", "我愛PUBG"); | |
UserNameField.text = PhotonNetwork.player.NickName; | |
if (UserNameField.text == "我愛PUBG" || string.IsNullOrWhiteSpace(UserNameField.text)) | |
{ | |
UserNameField.text = "我愛PUBG"; | |
} | |
else | |
{ | |
UserNameField.gameObject.SetActive(false); | |
UserName.gameObject.SetActive(true); | |
UserName.text = PhotonNetwork.player.NickName; | |
} | |
} | |
private void OnDestroy() | |
{ | |
PlayerPrefs.SetString("Username", UserNameField.text); | |
} | |
private void OnGUI() | |
{ | |
int ping = PhotonNetwork.GetPing(); | |
GUI.Label(new Rect(10, 10, 200, 30), PhotonNetwork.connectionStateDetailed.ToString() + "," + ping + " ms"); | |
} | |
//PhotonNetwork.autoJoinLobby is true | |
public override void OnJoinedLobby() | |
{ | |
lobbyPanel.SetActive(true); | |
NameBox.SetActive(true); | |
CreateBtn.SetActive(true); | |
//當玩家從遊戲中重返大廳 | |
Cursor.visible = true; | |
RoomListPanel.gameObject.SetActive(true); | |
GameRoomPanel.gameObject.SetActive(false); | |
HomeBtn.SetActive(false); | |
StartBtn.SetActive(false); | |
Debug.Log("已連上 Lobby"); | |
if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("GameScene")) | |
{ | |
PhotonManager.instance.lobbyPanel.SetActive(false); | |
PhotonManager.instance.NameBox.SetActive(false); | |
PhotonManager.instance.CreateBtn.SetActive(false); | |
PhotonManager.instance.RoomListPanel.gameObject.SetActive(false); | |
} | |
} | |
/// <summary> | |
/// Called after the connection to the master is established and authenticated | |
/// but only when PhotonNetwork.autoJoinLobby is false.If you set PhotonNetwork.autoJoinLobby to true, | |
/// OnJoinedLobby() will be called instead of this. | |
/// </summary> | |
public override void OnConnectedToMaster() | |
{ | |
// 連上 MasterServer 後, Button (UI) 就可以顯示或是執行其它後續動作. | |
CreateBtn.SetActive(true); | |
Debug.Log("已連上 Master Server"); | |
//JoinGameRoom(); | |
// AUTO Join Room for testing! | |
} | |
/// <summary> | |
/// 創建房间 | |
/// </summary> | |
public void CreateARoom() | |
{ | |
if (PhotonNetwork.connected) | |
{ | |
//創建房间成功 | |
if (PhotonNetwork.CreateRoom(UserNameField.text + " 的對戰室 ", new RoomOptions { MaxPlayers = 16 }, null)) | |
{ | |
Debug.Log("PhotonManager.CreateARoom 成功"); | |
StartCoroutine(GetInRoom()); | |
//GetInRoomMethod(); | |
} | |
} | |
} | |
/// <summary> | |
/// 加入已知房間房间 | |
/// </summary> | |
public void JoinGameRoom() | |
{ | |
RoomOptions options = new RoomOptions(); | |
options.MaxPlayers = 16; | |
PhotonNetwork.JoinOrCreateRoom(UserNameField.text + "'s Fighting Room", options, TypedLobby.Default); | |
StartCoroutine(GetInRoom()); | |
//GetInRoomMethod(); | |
} | |
public override void OnJoinedRoom() | |
{ | |
Debug.Log(PhotonNetwork.isMasterClient); | |
Debug.Log("您已進入遊戲室!!"); | |
PhotonNetwork.player.NickName = UserNameField.text; | |
if (!PhotonNetwork.isMasterClient) | |
{ | |
//For others not for the Host! | |
StartCoroutine(GetInRoom()); | |
//GetInRoomMethod(); | |
} | |
GameObject[] gos = GameObject.FindGameObjectsWithTag("PlayerItems"); | |
foreach (GameObject go in gos) | |
{ | |
print("OnJoinedRoom - Destroy(go)"); | |
if (!go.GetComponent<PhotonView>().isMine) | |
PhotonNetwork.Destroy(go); | |
else | |
Destroy(go); | |
} | |
if (PhotonNetwork.isMasterClient) | |
{ | |
players = PhotonNetwork.playerList; | |
foreach (PhotonPlayer player in players) | |
{ | |
lobbyPlayer = PhotonNetwork.InstantiateSceneObject("Lobby/PlayerItem", Vector3.zero, Quaternion.identity, 0, null); | |
if (player.ID % 2 == 1) | |
{ | |
player.SetTeam(PunTeams.Team.red); | |
lobbyPlayer.transform.SetParent(TeamA); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
else | |
{ | |
player.SetTeam(PunTeams.Team.blue); | |
lobbyPlayer.transform.SetParent(TeamB); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
Text Name = lobbyPlayer.transform.Find("PlayerName").GetComponent<Text>(); | |
Name.text = player.NickName + "(" + player.GetTeam() + " " + player.ID + ")"; | |
lobbyPlayer.name = player.NickName; | |
} | |
} | |
else | |
{ | |
StartCoroutine(InstantiateRemotePlayers()); | |
} | |
} | |
public override void OnPhotonPlayerConnected(PhotonPlayer newPlayer) | |
{ | |
if (PhotonNetwork.isMasterClient) | |
{ | |
lobbyPlayer = PhotonNetwork.InstantiateSceneObject("Lobby/PlayerItem", Vector3.zero, Quaternion.identity, 0, null); | |
if (newPlayer.ID % 2 == 1) | |
{ | |
newPlayer.SetTeam(PunTeams.Team.red); | |
lobbyPlayer.transform.SetParent(TeamA); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
else | |
{ | |
newPlayer.SetTeam(PunTeams.Team.blue); | |
lobbyPlayer.transform.SetParent(TeamB); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
Text Name = lobbyPlayer.transform.Find("PlayerName").GetComponent<Text>(); | |
Name.text = newPlayer.NickName + "(" + newPlayer.GetTeam() + " " + newPlayer.ID + ")"; | |
lobbyPlayer.name = newPlayer.NickName; | |
} | |
else | |
{ | |
//lobbyPlayer = GameObject.Instantiate(Resources.Load("Lobby/PlayerItem") as GameObject); | |
StartCoroutine(PlayerConnected(newPlayer)); | |
} | |
Debug.Log(PhotonNetwork.playerList.Length); | |
if (PhotonNetwork.playerList.Length > 15) | |
{ | |
PhotonNetwork.room.IsOpen = false; | |
} | |
else | |
{ | |
PhotonNetwork.room.IsOpen = true; | |
} | |
} | |
public override void OnPhotonPlayerDisconnected(PhotonPlayer otherPlayer) | |
{ | |
if (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("StartScene")) | |
{ | |
if (PhotonNetwork.isMasterClient) | |
{ | |
if (otherPlayer.GetTeam() == PunTeams.Team.red) | |
{ | |
lobbyPlayer = TeamA.Find(otherPlayer.NickName).gameObject; | |
PhotonNetwork.Destroy(lobbyPlayer); | |
} | |
else | |
{ | |
lobbyPlayer = TeamB.Find(otherPlayer.NickName).gameObject; | |
PhotonNetwork.Destroy(lobbyPlayer); | |
} | |
} | |
else | |
{ | |
if (otherPlayer.GetTeam() == PunTeams.Team.red) | |
{ | |
lobbyPlayer = TeamA.Find(otherPlayer.NickName).gameObject; | |
Destroy(lobbyPlayer); | |
} | |
else | |
{ | |
lobbyPlayer = TeamB.Find(otherPlayer.NickName).gameObject; | |
Destroy(lobbyPlayer); | |
} | |
} | |
Debug.Log(PhotonNetwork.playerList.Length); | |
//遊戲間最多16人,超過關閉 | |
if (PhotonNetwork.playerList.Length < 16) | |
{ | |
PhotonNetwork.room.IsOpen = true; | |
} | |
else | |
{ | |
PhotonNetwork.room.IsOpen = false; | |
} | |
} | |
} | |
public override void OnPhotonCreateRoomFailed(object[] codeAndMsg) | |
{ | |
Debug.Log("創建房间 faileds"); | |
} | |
//Note: When PhotonNetwork.autoJoinLobby is false, OnConnectedToMaster() will be called and the room list won't become available. | |
public override void OnReceivedRoomListUpdate() | |
{ | |
Debug.Log("OnReceivedRoomListUpdate"); | |
RoomInLobby[] roomsinlobby = RoomListPanel.GetComponentsInChildren<RoomInLobby>(); | |
foreach (RoomInLobby ril in roomsinlobby) | |
{ | |
Destroy(ril.gameObject); | |
} | |
//only check inside Lobby! | |
RoomInfo[] rooms = PhotonNetwork.GetRoomList(); | |
//Debug.Log(rooms.Length + " = 房間數量"); | |
foreach (RoomInfo room in rooms) | |
{ | |
GameObject g = Instantiate(Resources.Load("Lobby/RoomItem") as GameObject); | |
Text t = g.transform.Find("RoomName").GetComponent<Text>(); | |
t.text = room.Name; | |
g.name = room.Name; | |
g.GetComponent<RoomInLobby>().roomName = room.Name; | |
g.transform.SetParent(RoomListPanel); | |
g.transform.localScale = Vector3.one; | |
} | |
} | |
//只有MasterClient執行 | |
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) | |
{ | |
SceneManager.sceneLoaded -= OnLevelFinishedLoading; | |
// 若不在 Photon 的房間內,則網路有問題 | |
if (!PhotonNetwork.inRoom) return; | |
// 建立玩家的控制實體 | |
localPlayer = PhotonNetwork.Instantiate("Player3", new Vector3(0, 0, 0), Quaternion.identity, 0); | |
localPlayer.name = PhotonNetwork.player.NickName; | |
((MonoBehaviour)localPlayer.GetComponent("FirstPersonController")).enabled = true;//FpsCtrl enabled | |
localPlayer.GetComponentInChildren<TPSController>().enabled = true; //3rd animCtrl enabled | |
localPlayer.transform.GetChild(1).gameObject.SetActive(true); //1st body Active | |
localPlayer.transform.GetChild(0).GetChild(0).gameObject.SetActive(true); //Fps camera Active | |
localPlayer.transform.GetChild(2).GetChild(0).gameObject.layer = 20; //3rd body ignored | |
} | |
// 遊戲場景載入時觸發,使用在非同步載入 | |
private void OnLevelWasLoaded(int levelNumber) | |
{ | |
lobbyPanel.SetActive(false); | |
// 若不在Photon的遊戲室內, 則網路有問題.. | |
if (!PhotonNetwork.inRoom) return; | |
if (PhotonNetwork.isMasterClient) return; | |
Debug.Log("我們已進入遊戲場景了,耶~"); | |
//PhotonNetwork.Instantiate 在網路上建立個同步的物件, 這樣在所有連到這個Game Room的人都可以看到此物件 | |
localPlayer = PhotonNetwork.Instantiate("Player3", new Vector3(0, 0, 0), Quaternion.identity, 0); | |
localPlayer.name = PhotonNetwork.player.NickName; | |
((MonoBehaviour)localPlayer.GetComponent("FirstPersonController")).enabled = true;//FpsCtrl enabled | |
localPlayer.transform.GetChild(1).gameObject.SetActive(true); //1st body Active | |
localPlayer.transform.GetChild(2).GetChild(0).gameObject.layer = 20; //3rd body ignored | |
//localPlayer.transform.GetChild(0).GetChild(0).gameObject.SetActive(true); //Fps camera Active | |
} | |
public void StartGame() | |
{ | |
if (!PhotonNetwork.isMasterClient) | |
{ | |
PhotonPlayer player = PhotonNetwork.player; | |
PhotonView pv = GameObject.Find(player.NickName).GetPhotonView(); | |
pv.RPC("PressReadyBtn", PhotonTargets.AllBufferedViaServer); | |
return; | |
} | |
Room Gameroom = PhotonNetwork.room; | |
if (PhotonNetwork.playerList.Length < 8) | |
{ | |
SceneManager.sceneLoaded += this.OnLevelFinishedLoading; | |
//PhotonNetwork.LoadLevel("GameRoomScene"); ver1.0 | |
PhotonNetwork.LoadLevel("GameScene"); //ver1.2 | |
Gameroom.IsVisible = false; | |
} | |
} | |
public void ExitRoom() | |
{ | |
GameObject[] gos = GameObject.FindGameObjectsWithTag("PlayerItems"); | |
foreach (GameObject go in gos) | |
{ | |
Destroy(go); | |
print("ExitRoom - Destroy(go)"); | |
} | |
GameRoomPanel.gameObject.SetActive(false); | |
HomeBtn.SetActive(false); | |
StartBtn.SetActive(false); | |
PhotonNetwork.LeaveRoom(); | |
RoomListPanel.gameObject.SetActive(true); | |
CreateBtn.SetActive(true); | |
} | |
private IEnumerator GetInRoom() | |
{ | |
RoomListPanel.gameObject.SetActive(false); | |
CreateBtn.SetActive(false); | |
yield return new WaitForEndOfFrame(); | |
GameRoomPanel.gameObject.SetActive(true); | |
HomeBtn.SetActive(true); | |
StartBtn.SetActive(true); | |
} | |
private IEnumerator InstantiateRemotePlayers() | |
{ | |
yield return new WaitForSeconds(1); | |
//lobbyPlayer = GameObject.Instantiate(Resources.Load("Lobby/PlayerItem") as GameObject); | |
players = PhotonNetwork.playerList; | |
GameObject[] lobbyPlayers = GameObject.FindGameObjectsWithTag("PlayerItems"); | |
for (int index = 0; index < players.Length; index++) | |
{ | |
print(lobbyPlayers.Length + " / " + players.Length); | |
print(lobbyPlayers[index]); | |
print("OnJoinedRoom - Instantiate(go)" + lobbyPlayers[index]); | |
if (players[index].ID % 2 == 1) | |
{ | |
players[index].SetTeam(PunTeams.Team.red); | |
lobbyPlayers[index].transform.SetParent(TeamA); | |
lobbyPlayers[index].transform.localScale = Vector3.one; | |
} | |
else | |
{ | |
players[index].SetTeam(PunTeams.Team.blue); | |
lobbyPlayers[index].transform.SetParent(TeamB); | |
lobbyPlayers[index].transform.localScale = Vector3.one; | |
} | |
Text Name = lobbyPlayers[index].transform.Find("PlayerName").GetComponent<Text>(); | |
Name.text = players[index].NickName + "(" + players[index].GetTeam() + " " + players[index].ID + ")"; | |
lobbyPlayers[index].name = players[index].NickName; | |
} | |
} | |
private IEnumerator PlayerConnected(PhotonPlayer newPlayer) | |
{ | |
yield return new WaitForSeconds(1); | |
GameObject lobbyPlayer = GameObject.Find("PlayerItem(Clone)"); | |
//GameObject lobbyPlayer = GameObject.FindGameObjectWithTag("PlayerItems"); | |
print(lobbyPlayer + " ID :" + newPlayer.UserId); | |
print("PlayerConnected - Instantiate(go)" + lobbyPlayer); | |
if (newPlayer.ID % 2 == 1) | |
{ | |
newPlayer.SetTeam(PunTeams.Team.red); | |
lobbyPlayer.transform.SetParent(TeamA); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
else | |
{ | |
newPlayer.SetTeam(PunTeams.Team.blue); | |
lobbyPlayer.transform.SetParent(TeamB); | |
lobbyPlayer.transform.localScale = Vector3.one; | |
} | |
Text Name = lobbyPlayer.transform.Find("PlayerName").GetComponent<Text>(); | |
Name.text = newPlayer.NickName + "(" + newPlayer.GetTeam() + " " + newPlayer.ID + ")"; | |
lobbyPlayer.name = newPlayer.NickName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment