Hello everyone, I am trying to create an inventory for my game, and I would like to find out how to know if an object is inside a list, my script is like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory {
public string name;
public int health;
public Inventory(string newName, int newHealth) {
name = newName;
health = newHealth;
}
}
To add an object to my list I do the following:
List<Inventory> inventario = new List<Inventory> ();
inventario.Add (new Inventory ("Apple", 1));
What I want to do is to know if my list exists on the apple or any other object.
I think List.Contains will not work in this case - because Inventory is a class it’ll compare reference values, and won’t find it unless you do inventario.Contains(theExactInstanceYouAreCheckingFor)… which is probably not practical.
So to expand on the for loop:
for (int i=0; i< inventario.Count; i++) {
if (inventario[i].name == "Apple") {
// Yes
break; //don't need to check the remaining ones now that we found one
}
}
Well, a simple way is to just loop through your inventory. There isn’t anything wrong with using a loop.
You could also use something like the following
inventoryItem would be null if it doesn’t find anything or it will be the item in the list if it does find it, if you’re trying to interact with it somehow. (check it’s count, subtract from it, add to it, etc).
This isn’t quite correct. Contains uses the Equals implementation. So if you’ve overridden Equals, it’ll return true if you’re looking for a different object that is equal according to that method.
Of course, you’re otherwise correct in that it’s not a good solution here. You’ll probably not want to create a new inventory item just to check if a different one exists, even if there’s an Equals implementation.
If you just need to know if something named “apple” is in the list, and don’t need to do anything with it (for whatever reason), the built-in thing to do that is Linq’s Any: