- Home /
Problem with List in C#
I have made an list of players but for some reason the list always shows the last added player. How to fix this?
using UnityEngine; using System.Collections.Generic;
public class Player { public static int score;
public Player(int playerscore) {
score = playerscore;
}
public int Score {
get
{
return score;
}
set
{
score=value;
}
}
}
using UnityEngine;
using System.Collections.Generic;
using System;
public class Game : MonoBehaviour {
public static List<Player> players;
void Awake() {
players = new List<Player>();
}
void Start () {
players.Add(new Player(50));
players.Add(new Player(13));
players.Add(new Player(41));
players.Add(new Player(26));
}
public List<Player> Players { get { return players; } }
// Update is called once per frame
void Update () {
}
void OnGUI ()
{
GUI.Label(new Rect(150,10,50,25), players.Count.ToString());
GUI.Label(new Rect(10,10,50,25), players[0].Score.ToString());
GUI.Label(new Rect(50,10,50,25), players[1].Score.ToString());
}
}
I'm not sure if the question is clear. What do you mean by 'always shows the last added player'?
Answer by owenpat · Feb 28, 2011 at 02:15 AM
Looks like the problem is that the score (in public static int score;
in Player) is a static. Static means there is one copy for the entire class, no matter how few or many variables of that type there are. Each time you assign a score, it overwrites the ONE score all players share. Losing static
might cure it.
It's used if, say, you want one variable for maximum size, or a count of how many were made.
In C#, you commonly see it abused in fake classes which are really just a way to group functions, like in a Math class. Since your Game class below will always be created exactly once, it doesn't matter if players
is a static.
Your answer
