[RequireComponent(typeof(T)) is a completely different concept from implementing the interface T. (I’m expressing this in generic terms because this concept applies broadly.
We’ll start with the implementing the interface:
public class MyClass : MonoBehaviour, ISomeInterface
This tells the compiler that MyClass is a descendant of ParentClass, and that MyClass directly implements the ISomeInterface class.
[RequireComponent(typeof(ISomeInterface))]
public class MyClass : MonoBehaviour
This tells Unity that any GameObject that has the MyClass attached must also have at least one component attached that implements the ISomeInterface. This will be a different component.
Now let’s make this specific to our ItemTooltipSpawner and IItemHolder:
public interface IItemHolder
{
InventoryItem GetItem();
}
Our interface specifies that any class that implements IItemHolder must have a public or qualified method InventoryItem GetItem()
In our InventorySystem we implement this class InventorySlotUI, EquipmentSlotUI, and ActionSlotUI. For example:
public class InventorySlotUI : MonoBehaviour, IItemHolder, IDragContainer<InventoryItem>
In this case, the InventorySlotUI implements the IItemHolder with this method:
public InventoryItem GetItem()
{
return inventory.GetItemInSlot(index);
}
We want ItemTooltipSpawner to work with any of these three classes (or any other class you might create that has a tooltip you want to display, like a shop item in the Shops and Abilities course!). We also want to ensure that when we put an ItemTooltipSpawner on a GameObject, that it most certainly does have an IItemHolder implemented class on it. This is why we have
[RequireComponent(typeof(IItemHolder))]
RequireComponent is a special Unity only attribute that only makes sense with MonoBehaviours, i.e. things that are attached to GameObjects. It performs validiations when you try to remove a component from the GameObject… Unfortunately, it does not always automatically attach an item for you, specifically, since we’re requiring an Interface item, it doesn’t know which actual class you want to add… but assuming that the IItemHolder class is already there, it won’t let you remove that component until the ItemTooltipSpawner is removed.
You can test this by
- Creating an empty GameObject.
- Now on your empty GameObject, add an InventorySlotUI component.
- Try removing the component, and you can see that you can remove it normally.
- Add the InventorySlotUI component again
- Add an ItemTooltipSpawner
- Try removing the InventorySlotUI component. You’ll see that you can’t remove it.
- Remove the ItemTooltipSpawner
- Try removing the InventorySlotUI component. You’ll see that you can now remove it normally.