Unity 3d光子引擎其他玩家如何获取master客户端生成的数据



你好,我需要帮助制作一款带光子的在线双人游戏。每个玩家都会收到一个生成的票号,玩家1将成为访客玩家2的票号。玩家2将成为访客,同时也是玩家1的票号。

下面是主客户端生成票证的脚本。当玩家2加入房间时,他将从玩家1(主客户端(生成的门票中获得门票。我创建了一个带有照片视图的游戏对象,脚本在这里

void Start()
{
if (PhotonNetwork.IsMasterClient)
{
player1ticket = UnityEngine.Random.Range(1000, 5000);
player2ticket = UnityEngine.Random.Range(1000, 5000);
}
getTicket = true;
}
// Update is called once per frame
void Update()
{
if (getTicket)
{
if (PhotonNetwork.IsMasterClient)
{
myTicket = player1ticket;
}
else
{
myTicket = player2ticket;
}
getTicket = false;
}
}

但是当玩游戏时,玩家2没有任何票号

首先,您知道可能会发生两个都得到相同的票号的情况——不太可能,但有可能。在这种情况下,你可能想重复第二次随机

player1ticket = UnityEngine.Random.Range(1000, 5000);
do
{
player2ticket = UnityEngine.Random.Range(1000, 5000); 
} 
while(player2ticket == player1ticket);   

那么,你只能在master中生成值。因此,在客户端上,getTicket永远不是true

即使是这样,客户端也没有player2ticket值。

也没有必要/感觉到在"更新"中为每一帧指定它们。


我宁愿使用自定义房间属性,在主机上使用Room.SetCustomProperties,这将在所有客户端上触发OnRoomPropertiesUpdate(Hashtable。这个呼叫也会在客户端加入房间后触发一次,这样你就可以确保新连接的客户端不会错过它

void Start()
{
if (PhotonNetwork.IsMasterClient)
{
player1ticket = UnityEngine.Random.Range(1000, 5000);
player2ticket = UnityEngine.Random.Range(1000, 5000);
// You are master so already get your ticket
myTicket = player1ticket;
// Then simply push the other ticket(s) into the room properties
Hashtable properties = PhotonNetwork.room.customProperties; 
properties["ticket2"] =  player2ticket);  
// This will store the value in the current room
// and triggers OnRoomPropertiesUpdate on all already connected clients
PhotonNetwork.room.SetCustomProperties(properties);
}
}
// This will be called
// - as soon as you entered a room
// - whenever someone writes into the room properties
public override void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
// Not sure about the exact API right now, it's not in their docs
// it's either ContainsKey, HasKey or something similar ..maybe even TryGetValue works
if(!propertiesThatChanged.ContainsKey("ticket2")) return;
if(!PhotonNetwork.IsMasterClient)
{
myTicket = (int) PhotonNetwork.room.customProperties["ticket2"];
}
}

最新更新