- Home /
String list contains method returns false from game object name
Hi guys,
Simply what I am trying to do is add items to an inventory list - a string list - by their object name. The setup is that on adding an object to the inventory in game, the script takes the name from the raycasthit - for these purposes "hit" is my raycasthit object - information using hit.collider.gameObject.ToString()
, and I have also tried with hit.collider.gameObject.name
and adds it to a string list called inventory, then destroys the item in game.
Now I have checked using a Debug.Log()
in a foreach string item that the inventory list and it always returns the string I'm looking for from the list. However, when I try and perform any checks using the List.Contains()
method it always returns false.
For example:
//Some game object called "Ring"
inventory.Add(hit.collider.gameObject.ToString()); //Adds Ring as far as the Debug.Log shows.
if(inventory.Contains("Ring")) {
//Something
}
else if(!inventory.Contains("Ring")) {
//Something else
}
Despite what I try it always returns false despite a debug log which seems to show it should be true. Why might that be? I've tried, as I've said, also using name instead but to no avail.
Any ideas?
Kindest
Perhaps a GameObject's ToString method returns its name variable directly, I'm not sure. Using gameObject.name is much better for readability regardless.
Not sure why your example isn't working, but using strings for such a purpose, especially hard-coded literals, is not a wise practice where avoidable. $$anonymous$$ake sure your game object's name is what you expect it to be (e.g. no extra space at the end, case sensitive, not a (clone), etc).
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Delete first object of the same type in a list? C# 1 Answer
List.Contains Method wont work. 1 Answer
Comparing two lists to find the difference 1 Answer
Voting System Using List (C#) 1 Answer