Search for objects in a list..

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 hope you can help me, thank you very much.

PS: I’m sorry for my English D:

List.Contains will work for simple cases. For a more sophisticated approach you can use a for loop and iterate accross the entire list.

2 Likes

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
}
}
7 Likes

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

Inventory inventoryItem = inventario.Find((x) => x.name == someString);

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).

6 Likes

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:

bool hasApple = inventario.Any(x => x.name == "Apple");
7 Likes

Thanks to everyone for the help, in the end I ended up doing it this way.

void Buscar (string nombre)
    {




        Inventory item = inventario.Find(x=> x.name == nombre);

        if(item == null){
            Debug.Log ("No hay manzanas");
        }
        else{
            Debug.Log ("Si hay manzanas");
        }




       
    }
5 Likes

Gracias desde la francia! me has salvado la vida

1 Like