- Home /
Creating an array of player scores with Unity Multiplayer
For my game, two players (Server and Client) are spawned. When a certain event takes place, their score is incremented by 1. INDIVIDUALLY, this works, as each player object has a PlayerScript attached which stores their score as a float (the float is because certain calculations and conversions need this).
My goal here is to create an array of the score of each player. Something like this...
public float scores[] = new float[2];
scores[0] = firstPlayerScore;
scores[1] = secondPlayerScore;
However, after consulting dozens of tutorials and online ressources, I am completely unable to figure out how to fetch the other player's score. I've tried to work with SyncVar, ClientRpc and Commands, but nothing seems to work. Heres the script I have now :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class PlayerScript : NetworkBehaviour {
[SyncVar]
public float score; // Store the players score
[SyncVar]
public float otherScore; // Store the second players score
SyncListFloat scores = new SyncListFloat();
public GameObject gm; // The GameManager
public Canvas FinishedCanvas;
// Use this for initialization
void Start () {
gm = GameObject.FindWithTag("GameManager"); // Find the GameManager
FinishedCanvas = GameObject.Find("FinishedCanvas").GetComponent<Canvas>();
FinishedCanvas.gameObject.SetActive(false);
}
// Update is called once per frame
void Update () {
if(!isLocalPlayer)
{
return;
}
score = getScore(gm.GetComponent<CardManager>().playerScore, gm.GetComponent<CardManager>().periodIDs.Length); // Get the score as a percentage
Debug.Log(score);
CmdUpdateScore(score);
if (gm.GetComponent<CardManager>().isDone())
{
scores.Add(score);
scores.Add(otherScore);
Debug.Log(score);
}
}
public float getScore(float s, float t) {
return (s / t) * 100; // Return a percentage
}
[Command]
public void CmdUpdateScore(float s)
{
score = s;
}
}
As you can see, I also have a float called "otherScore", which was my attempt at separating the two scores, but of course, it doesn't result to anything.
How would I go about resolving this issue?
Thank you
Your answer
![](https://koobas.hobune.stream/wayback/20220612131833im_/https://answers.unity.com/themes/thub/images/avi.jpg)