I made a custom class (Item), which is used to store data of an item, all stored in a List. When checking if an item is present in the list, I always have to test if (list != null). Though this works so far, it would be much better to be able to test if (list*) like with GameObjects (which either return their name or null).*
So, my question is: When I have a custom class Item, a list storing these items List storedItems and certain positions in the list occupied with items and others empty (null), how do I make if (storedItems[index]) return either true (if the item exists) or false (if the item doesn’t exist)? GameObjects already work like this (the “bool” operator, as described in the reference manual), but I haven’t managed to find appropriate keywords to find it online.
Thanks!
This is not the usual way how classes work. Unity does implement a custom conversion operator for UnityEngine.Object for convenience.
You can also implement an implicit conversion operator into a “bool”:
public class Item
{
public static implicit operator bool(Item aItem)
{
return aItem != null;
}
}