- Home /
How do I set a custom return value when using a custom class?
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[i] != null). Though this works so far, it would be much better to be able to test if (list[i]) 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!
Answer by Bunny83 · Aug 28, 2017 at 05:06 PM
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;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612133729im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Inspector button for custom class 1 Answer
Custom Documentation for Monodevelop 1 Answer
Magic Spell Types - SpellType.Fire/Water/Earth? 1 Answer
Share Public Classes 1 Answer
Left 4 Dead-style Spawnpoints? 1 Answer