facebook twitter hatena line email

Unity/photon/pun2/helloworld

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

LobbyScene.cs

using UnityEngine;
using UnityEngine.UI;

public class LobbyScene : MonoBehaviour
{
	PhotonManager photonManager;
	void Start()
	{
		GameObject.Find("InputField").GetComponent<InputField>().text = "room1";
		GameObject.Find("Button").GetComponent<Button>().onClick.AddListener(OnClick);
	}
	void OnResponseConnect(PhotonManager.ResponseType responseType)
	{
		if (responseType.Equals(PhotonManager.ResponseType.JoinedRoom))
		{
			// SceneManager.LoadScene("RpcViewScene");
		}
	}
	void OnClick()
	{
		string roomId = GameObject.Find("InputField").GetComponent<InputField>().text;
		photonManager = PhotonManager.Instance;
		photonManager.AddCallback(OnResponseConnect);
		photonManager.roomId = roomId;
		photonManager.userId = "user" + Random.RandomRange(1, 1000);
		photonManager.ConnectStart();
	}
}

PhotonManager.cs

using System.Collections.Generic;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Linq;

public class PhotonManager : MonoBehaviourPunCallbacks
{
	public string roomId = "room1";
	public string userId = "user1";
	private static PhotonManager mInstance;
	private PhotonManager()
	{
	}
	public static PhotonManager Instance
	{
		get
		{
			if (mInstance == null)
			{
				GameObject go = new GameObject("PhotonManager");
				mInstance = go.AddComponent<PhotonManager>();
			}
			return mInstance;
		}
	}
	public enum ResponseType
	{
		JoinedRoom,
	}
	public delegate void PhotonCallback(ResponseType responseType);
	private PhotonCallback photonCallbacks;
	public void AddCallback(PhotonCallback callback)
	{
		photonCallbacks += callback;
	}
	public void ConnectStart()
	{
		Debug.Log("ConnectStart");
		if (PhotonNetwork.IsConnected == false)
		{
			PhotonNetwork.ConnectUsingSettings();
			PhotonNetwork.GameVersion = "v1.0";
		}
	}
	// マスターサーバーに接続した時
	public override void OnConnectedToMaster()
	{
		Debug.Log("OnConnectedToMaster");
		if (PhotonNetwork.IsConnected)
		{
			PhotonNetwork.JoinLobby();
		}
	}
	public override void OnJoinedLobby()
	{
		Debug.Log("OnJoinedLobby");

		// PhotonNetwork.JoinRandomRoom();
		CreateRoom();
	}
	public void CreateRoom()
	{
		string userName = "ユーザ" + userId;
		ExitGames.Client.Photon.Hashtable customProp = new ExitGames.Client.Photon.Hashtable();
		customProp.Add("userName", userName);
		customProp.Add("userId", userId);
		PhotonNetwork.SetPlayerCustomProperties(customProp);
		RoomOptions roomOptions = new RoomOptions();
		roomOptions.CustomRoomProperties = customProp;
		roomOptions.CustomRoomPropertiesForLobby = new string[] { "userName", "userId" };
		roomOptions.MaxPlayers = 5; // 部屋の最大人数
		roomOptions.IsOpen = true; // 入室許可する
		roomOptions.IsVisible = true; // ロビーから見えるようにする
		PhotonNetwork.JoinOrCreateRoom(roomId, roomOptions, null);

	}
	public void JoinPrivateRoom(string roomName)
	{
		PhotonNetwork.JoinRoom("p" + roomName);
		JoinPrivateRoomName = roomName;
	}
	// JoinRoom()呼び出し、失敗時
	public override void OnJoinRoomFailed(short returnCode, string message)
	{
		Debug.Log("PhotonManager OnPhotonJoinRoomFailed " + returnCode + " " + message);
	}
	// ルーム入室した時
	public override void OnJoinedRoom()
	{
		Debug.Log("OnJoinedRoom");
		RoomInfo r = PhotonNetwork.CurrentRoom;
		Debug.Log("roomname=" + r.Name); // 部屋名
		Debug.Log("PlayerCount=" + r.PlayerCount); // 現在の人数
		Debug.Log("maxPlayer=" + r.MaxPlayers); // 最大人数
		Debug.Log("userId=" + userId);

		SceneManager.LoadScene("RpcViewScene");
	}
	public override void OnRoomListUpdate(List<RoomInfo> roomList)
	{
		Debug.Log("OnRoomListUpdate");
		List<RoomInfo> tmpRoomList = roomList.Where(s => s.IsOpen).ToList();
		if (tmpRoomList.Count == 0)
		{
			Debug.Log("ルームが一つもありません");
		}
		else
		{
			foreach (RoomInfo room in tmpRoomList)
			{
				Debug.Log("RoomName:" + room.Name);
				Debug.Log("PlayerName:" + room.CustomProperties["PlayerName"]);
			}
		}
	}

	public override void OnJoinRandomFailed(short returnCode, string message)
	{
		string userName = "ユーザ" + userId;
		ExitGames.Client.Photon.Hashtable customProp = new ExitGames.Client.Photon.Hashtable();
		customProp.Add("userName", userName);
		customProp.Add("userId", userId);
		PhotonNetwork.SetPlayerCustomProperties(customProp);
		RoomOptions roomOptions = new RoomOptions();
		roomOptions.CustomRoomProperties = customProp;
		roomOptions.CustomRoomPropertiesForLobby = new string[] { "userName", "userId" };
		roomOptions.MaxPlayers = 2; // 部屋の最大人数
		roomOptions.IsOpen = true; // 入室許可する
		roomOptions.IsVisible = true; // ロビーから見えるようにする
		// roomnameをnullとすると7d60e607-263f-4360-8bf9-51b3d4ae2348な感じのnameになる
		PhotonNetwork.CreateRoom(null, roomOptions, null);
	}
	
	// 自分以外が入室
	public override void OnPlayerEnteredRoom(Player player)
	{
		Debug.Log("OnPlayerEnteredRoom " + player.NickName + " is joined.");
                // PhotonNetwork.PlayerListOthers
	}
	// 自分でないメンバーを一人返す
	public string OtherMemberName() {
		foreach (var p in PhotonNetwork.PlayerListOthers) {
			if (!PhotonNetwork.NickName.Equals(p.NickName)) {
				return p.NickName;
			}
		}
		return "";
	}
	public void Disconnect()
	{
		if (PhotonNetwork.IsConnected)
		{
			PhotonNetwork.LeaveRoom();
		}
		PhotonNetwork.Disconnect();
	}
}

画面遷移時でも使えるように

DontDestroyOnLoadを追加する

if (mInstance == null)
{
	GameObject go = new GameObject("PhotonManager");
	mInstance = go.AddComponent<PhotonManager>();
	DontDestroyOnLoad(go);
}

部屋に参加したときのPhotonNetwork.PlayerListについて

(2024/9/17時点)

部屋に参加した(JoinedRoom)ときの、相手の情報が、PhotonNetwork.PlayerListに登録されてない場合があったため、 0.1秒遅らせて、処理したら、相手の情報が、載っていた。

その他

公式マニュアル:https://doc-api.photonengine.com/ja-jp/pun/current/class_photon_1_1_pun_1_1_mono_behaviour_pun_callbacks.html

OnCreatedRoom() 

このクライアントがルームを作成して入室すると呼び出されます。 OnJoinedRoom ()も呼び出されます