我正在尝试使用Photon Unity Networking创建一个简单的基于2D Turn的多人游戏。
这只是一个简单的回合制游戏,其中player 1
(主持人)按下他的按钮并添加他的分数并改为转向player 2
(客户),按下他的按钮以增加分数和改为转为player 1
。它继续无限。
我能够使用基本的Photon
文档连接游戏中的两个玩家。现在我需要添加轮流和更改它们的网络逻辑。
我搜索了互联网,但我无法理解Photon的RPC
和SerializeView
。我真的很困惑。请帮我。谢谢你将来。这是我的GameManager
脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : Photon.PunBehaviour
{
public Text roomName;
public Text player1Name,player2Name;
public List<string> playersConnected = new List<string>();
int scoreP1 = 0, scoreP2 = 0;
public Text scoreTextP1, scoreTextP2;
public Button p1Btn, p2Btn;
int playerTurn = 1;
void Start()
{
roomName.text = SceneManager.GetActiveScene().name;
p2Btn.gameObject.SetActive(false);
p1Btn.gameObject.SetActive(true);
}
public void AddScoreP1()
{
scoreP1++;
scoreTextP1.text = scoreP1.ToString();
ChangePlayerTurn();
}
public void AddScoreP2()
{
scoreP2++;
scoreTextP2.text = scoreP2.ToString();
ChangePlayerTurn();
}
void ChangePlayerTurn()
{
if (playerTurn == 1)
{
playerTurn = 2;
p2Btn.gameObject.SetActive(true);
p1Btn.gameObject.SetActive(false);
}
else
{
playerTurn = 1;
p1Btn.gameObject.SetActive(true);
p2Btn.gameObject.SetActive(false);
}
print("Player Turn: P" + playerTurn);
}
void LoadArena()
{
if (!PhotonNetwork.isMasterClient)
{
Debug.LogError("PhotonNetwork : Trying to Load a level but we are not the master Client");
}
Debug.Log("PhotonNetwork : Loading Level : " + PhotonNetwork.room.PlayerCount);
PhotonNetwork.LoadLevel("Room for " + PhotonNetwork.room.PlayerCount);
}
public override void OnLeftRoom()
{
SceneManager.LoadScene(0);
}
public void LeaveRoom()
{
PhotonNetwork.LeaveRoom();
}
public override void OnPhotonPlayerConnected(PhotonPlayer other)
{
Debug.Log("OnPhotonPlayerConnected() " + other.NickName); // not seen if you're the player connecting
foreach (PhotonPlayer _player in PhotonNetwork.playerList)
{
playersConnected.Add(other.NickName);
}
if (PhotonNetwork.isMasterClient)
{
Debug.Log("OnPhotonPlayerConnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected
LoadArena();
}
}
public override void OnPhotonPlayerDisconnected(PhotonPlayer other)
{
Debug.Log("OnPhotonPlayerDisconnected() " + other.NickName); // seen when other disconnects
foreach (PhotonPlayer _player in PhotonNetwork.playerList)
{
playersConnected.Remove(other.NickName);
}
if (PhotonNetwork.isMasterClient)
{
Debug.Log("OnPhotonPlayerDisonnected isMasterClient " + PhotonNetwork.isMasterClient); // called before OnPhotonPlayerDisconnected
LoadArena();
}
}
}
答案 0 :(得分:1)
RPC基本上是在远程客户端上调用功能的一种方式。
通常,在多人游戏设置中,您希望MasterClient控制游戏流程。因此,当两个玩家进入一个房间时,您需要从MasterClient进行操作,确定哪个玩家先进入,然后从MasterClient调用RPC函数,告诉两个客户端第一个回合。然后,无论轮到哪个玩家,只需激活其按钮并让他们添加得分(为此也将RPC发送到MasterClient,以便每个人都可以保持同步。),然后更新就可以通过另一个RPC告诉每个人,依此类推。 / p>
尽管您也可以在此类情况下使用事件,但事件准备工作较少。