zligg
zligg

Reputation: 49

How to print the position of a gameObject in a list?

I have a list and text:

List<GameObject> EnteredPlayers = new List<GameObject>();
public Text finishText;

When the player enters the trigger, they will be added to the list:

if (col.gameObject.tag == "finish") {

        EnteredPlayers.Add(player);
        finishText.text = //player's position in list here
    }

I would like to print the player's position in the list. For example, if their position is [0] then the text would say 1st place.

Any idea how I can do this?

Upvotes: 1

Views: 105

Answers (1)

krlzlx
krlzlx

Reputation: 5822

// Add the player
EnteredPlayers.Add(player);

// Get the position
int position = EnteredPlayer.Count

// Create a dictionary with the position names
// Put this dictionary outside of your method managing the games
Dictionary<string, string> positionNames = new Dictionary<string, string>(){
    { "1", "First" },
    { "2", "Second" },
    { "3", "Third" }
};

// Assign the label text
finishText.Text = positionNames[position.ToString()]; 

Upvotes: 3

Related Questions