我使用Unity Engine为Android制作游戏,我使用Google Play游戏服务进行多人游戏。当我向其他玩家发送字符串消息时,我遇到了问题。我可以发送它,但其他玩家不能收回它。
发送代码:
public void SendMyUpdate(float posX, float posZ, Vector3 velocity, float rotY, float weapon, string opponentId)
{
DebugConsole.Log("OppenentSend " + opponentId);
bytesize = opponentId.Length * sizeof(byte);
_updateMessageLength = 26 + bytesize;
_updateMessage.Clear();
_updateMessage.Add(_protocolVersion);
_updateMessage.Add((byte)'U');
_updateMessage.AddRange(BitConverter.GetBytes(posX));
_updateMessage.AddRange(BitConverter.GetBytes(posZ));
_updateMessage.AddRange(BitConverter.GetBytes(velocity.x));
_updateMessage.AddRange(BitConverter.GetBytes(velocity.z));
_updateMessage.AddRange(BitConverter.GetBytes(rotY));
_updateMessage.AddRange(BitConverter.GetBytes(weapon));
//_updateMessage.AddRange(BitConverter.GetBytes(opponentHp));
_updateMessage.AddRange(System.Text.Encoding.UTF8.GetBytes(opponentId));
byte[] messageToSend = _updateMessage.ToArray();
PlayGamesPlatform.Instance.RealTime.SendMessageToAll(false, messageToSend);
}
Recived Code:
public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
{
// We'll be doing more with this later...
byte messageVersion = (byte)data[0];
// Let's figure out what type of message this is.
char messageType = (char)data[1];
if (messageType == 'U' && data.Length == _updateMessageLength)
{
float posX = BitConverter.ToSingle(data, 2);
float posZ = BitConverter.ToSingle(data, 6);
float velX = BitConverter.ToSingle(data, 10);
float velZ = BitConverter.ToSingle(data, 14);
float rotY = BitConverter.ToSingle(data, 18);
float weapon = BitConverter.ToSingle(data, 22);
//int opponentHp = BitConverter.ToInt16(data, 26);
string opponentId = System.Text.Encoding.UTF8.GetString(data);
// We'd better tell our GameController about this.
if (updateListener != null)
{
updateListener.UpdateReceived(senderId, posX, posZ, velX, velZ, rotY, weapon, opponentId);
DebugConsole.Log("OppenentRecived " + opponentId);
}
}
else if (messageType == 'F' && data.Length == _finishMessageLength)
{
// We received a final time!
float finalTime = System.BitConverter.ToSingle(data, 2);
//Debug.Log ("Player " + senderId + " has finished with a time of " + finalTime);
}
这是从这个代码 https://www.raywenderlich.com/87042/creating-cross-platform-multi-player-game-unity-part-2
答案 0 :(得分:0)
您应该记得添加转换器应该找到字节范围的索引
ie: string opponentId = System.Text.Encoding.UTF8.GetString(data, int index);