Hey all,
I’m working on a LAN Multiplayer game at the moment, and the system is bare-bones but working as intended; except for synchronization of scores.
What I’m trying to achieve is having the scores of player A and player B on the screen for the client and the host. At the moment, with the code provided, the score for the host (player 1) is synchronized across the client but not the other way around. The client machine score doesn’t update across the network.
using UnityEngine;
using System.Collections;
public class gameplayManager : MonoBehaviour
{
private gameplayManager otherPlayer;
private int otherScore;
private networkManager nManager;
private bool guiEnabled;
private bool gameStarted;
public int myScore;
public GUISkin guiSkin;
void Start()
{
nManager = gameObject.GetComponent<networkManager>();
guiEnabled = false;
gameStarted = false;
myScore = 0;
otherScore = 0;
if (!networkView.isMine)
{
gameObject.tag = "otherPlayer";
}
else
{
gameObject.tag = "localPlayer";
otherPlayer = GameObject.FindWithTag("otherPlayer").GetComponent<gameplayManager>();
}
}
void Update()
{
// Check player count, end the game if there's less than specified.
if (nManager.GetConnectionCount() != 1 && gameStarted)
{
networkView.RPC("SetConnectionState", RPCMode.AllBuffered, 3);
guiEnabled = false;
gameStarted = false;
}
else
{
if (networkView.isMine)
{
if (otherPlayer != null)
{
otherScore = otherPlayer.myScore;
}
}
}
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
int tScore = 0;
if (stream.isWriting)
{
tScore = myScore;
stream.Serialize(ref tScore);
}
else
{
stream.Serialize(ref tScore);
myScore = tScore;
}
}
void OnGUI()
{
GUI.skin = guiSkin;
if (guiEnabled)
{
if (!networkView.isMine)
{
GUI.Label(new Rect(16, 16, 128, 24), "Player 1: " + myScore);
GUI.Label(new Rect(16, 40, 128, 24), "Player 2: " + otherScore);
if (GUI.Button(new Rect(Screen.width / 2 - 128, Screen.height / 2 - 20, 256, 32), "Click to add to myScore"))
{
otherScore += 10;
}
}
else
{
GUI.Label(new Rect(16, 16, 128, 24), "Player 1: " + myScore);
GUI.Label(new Rect(16, 40, 128, 24), "Player 2: " + otherScore);
if (GUI.Button(new Rect(Screen.width / 2 - 128, Screen.height / 2 - 20, 256, 32), "Click to add to myScore"))
{
myScore += 10;
}
}
}
}
[RPC]
void StartGame()
{
guiEnabled = true;
gameStarted = true;
}
}
Your help with this matter is much appreciated, thank you.