- Home /
Generic List 'Contains' always returns false
Hi,
I am trying out the Contains method for generic Lists, but for some reason it keeps returning false. My goal is to check if a player exists in the Players class.
Here is the code I am testing:
#pragma strict
import System.Collections.Generic;
var playersList = new List.<Players>();
class Players
{
var name : String;
}
function Start ()
{
//Add Player for testing
var addPlayer = new Players();
addPlayer.name = "Bob";
playersList.Add(addPlayer);
//Check if player exists
var checkPlayerByName = new Players();
checkPlayerByName.name = playersList[0].name;
//Check to see if playersList.Contains(checkPlayerByName) returns true
print("Player Exists = " + playersList.Contains(checkPlayerByName));
//Does not return true. Why?
}
Any ideas?
Thanks!
Answer by HappyMoo · Jan 19, 2014 at 07:15 PM
Please Name your Players class "Player" as it only represents one player, not many "Players"
You ask if a certain instance is in the List and it's not. You have two instances - addPlayer and checkPlayerByName - and they are different, even if you set their name to be the same.
It's like if you know two Bobs - they have the same Name, but they are different persons.
If you want something like that, use a generic Dictionary or a Javascript Object associative array to store the players by name.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130852im_/https://answers.unity.com/themes/thub/images/avi.jpg)