导入Photon2插件......
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.UI;
using Photon.Realtime;
public class NetworkLuncher : MonoBehaviourPunCallbacks//继承回调行为类
{
public GameObject nameUI;
public GameObject loginUI;
public InputField name;
public InputField roomName;
// Start is called before the first frame update
void Start()
{
//链接服务器
PhotonNetwork.ConnectUsingSettings();
}
//链接到服务器后执行
public override void OnConnectedToMaster()
{
nameUI.SetActive(true);
}
//输入名字的确认按钮
public void PlayButton()
{
nameUI.SetActive(false);
PhotonNetwork.NickName = name.text;
loginUI.SetActive(true);
}
//创建房间加入房间按钮
public void JoinOrCreatButton()
{
//如果没有输入=》退出方法在此输入
if (roomName .text .Length <2)
{
return;
}
loginUI.SetActive(false);
//服务器房间设置:房间类型,最大玩家数
RoomOptions options = new RoomOptions { MaxPlayers = 4 };
//加入/创建房间
PhotonNetwork.JoinOrCreateRoom(roomName .text, options, default);
}
//进入到服务器房间后执行
public override void OnJoinedRoom()
{
//进入房间后进入下一场景
PhotonNetwork.LoadLevel(1);
}
}
//按下准备开始按钮
(using Photon.Pun;)
public void StrtPlay()
{
readyPanel.SetActive(false);
//生成预制体玩家
PhotonNetwork.Instantiate("Player", new Vector3(1, 1, 0), Quaternion.identity, 0);
}
//控制本地角色
using Photon.Pun;
public class PlayerCT : MonoBehaviourPun
//房间列表
1.初始脚本中链接服务器时,加入大厅
//链接到服务器后执行
public override void OnConnectedToMaster()
{
nameUI.SetActive(true);
PhotonNetwork.JoinLobby();
}
//程序
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
public class RoomManager : MonoBehaviourPunCallbacks
{
public GameObject roomNamePrefab;//显示列表的按钮
public Transform gridLayout;
public override void OnRoomListUpdate(List<RoomInfo> roomList)//房间列表更新是执行
{
for (int i = 0; i < gridLayout.childCount; i++)
{
if(gridLayout .GetChild (i).gameObject. GetComponentInChildren<Text >().text ==roomList [i].Name )
{
//以存在的房间发生变化时消除该房间
Destroy(gridLayout.GetChild(i).gameObject);
if (roomList [i].PlayerCount ==0)//房间中人数为0是移除该房间
{
roomList.Remove(roomList[i]);
}
}
}
foreach (var room in roomList )//生成已存在的房间
{
GameObject newRoom = Instantiate(roomNamePrefab, gridLayout.position, Quaternion.identity);
roomNamePrefab.GetComponentInChildren<Text>().text = room .Name ;
newRoom.transform.SetParent(gridLayout);
}
}