- Home /
How to display connections count on client
I have a simple code :
loadingText.text ="Gathering additional players " + NetworkServer.connections.Count + "/4";
(loadingText is a GUI text element under canvas) but NetworkServer only works for the Server and not for a client (obviously)
Is there a similar solution for clients ?
or
Is there a way i can sync the text component or gameObject to client ?
Answer by Zahiro · Oct 21, 2016 at 05:17 PM
I used SyncVar to solve the problem
[SyncVar]
public int playersConnected;
void Update () {
if (displayPlayers) {
//only server is allowed to announce player count since he is the only that can count them
if (Network.isServer) {
playersConnected = NetworkServer.connections.Count;
}
loadingText.text = "Gathering additional players " + playersConnected + "/4";
}
}
Simplified : It's a variable that is shared over the network session/connection so, for example, if the SyncVar "playersConnected" changes to, let's say, "3" then this variable is "3" for all the connections aka players. !Be aware that ONLY servers(in this case the host) can change a SyncVar so a simple boolean check like "if (Network.isServer)" as the above example is perfect
where to put the networkbehavior script? when I put the script in the main camera, the camera will disabled,
then where to put the codes? server side or client side? because i separate the server and client
i tried it on client side but returning "0" ins$$anonymous$$d of "1".
then i want to know how client get the value of "playerconnected" if it's change in the server in different script.
lets say server is script A while client is script B. how they can communicate using [syncvar]?
I'm hoping for your help!. thanks
Answer by Gaidzin · Nov 01, 2017 at 02:37 PM
NetworkServer.connections may be nulls in this list for disconnected clients. It not really count of connections.
Answer by BjoUnity3d · Jul 08, 2018 at 10:05 PM
As Gaidzin said, Since NetworkServer.connections.Count can have nulls it doesn't give you the actual number of connected clients. This is how I got the actual count.
int GetConnectionCount()
{
int count = 0;
foreach (NetworkConnection con in NetworkServer.connections)
{
if (con != null)
count++;
}
return count;
}
Answer by sundayhd5 · Jan 20, 2021 at 08:18 PM
This what I did:
public class NetworkPlayer : NetworkBehaviour
{
private static int count = 0;
private void Awake()
{
count++;
}
private void OnDestroy()
{
count--;
}
private void Start()
{
if (isLocalPlayer)
{
transform.name = "NetworkPlayer (Local)";
}
else
transform.name = "NetworkPlayer (Network)";
print($"{transform.name}, total players: {count}");
}