I’m wondering if I can achieve something elegantly without using inheritance.
I have an Item class, with a Use coroutine. The Use coroutine performs a timed action, and then yields back to the controller. Currently, types of Items simply inherit Item and override the Use coroutine.
If I didn’t have to wait for the coroutine, I could just SendMessage(“OnUse”); and implement item types as components with [RequireComponent(typeof(Item))], but I really need the coroutine for scripting sequences of events.
It’s not that I critically need to avoid inheritance, I’m just wondering if there’s a solution which doesn’t require it.
You could make Item an interface that requires an IEnumerator Use() method implementation instead of making it a class. Your RequireComponent attribute wouldn’t work anymore though.
Why don’t you want to use inheritance?
It’s not that I don’t want to use inheritance, the question is academic, I was just wondering if it was possible to achieve the same result via messages or events or delegates or maybe some clever combination of basic C# actions I hadn’t considered!
You don’t need any of that.
public interface Item
{
IEnumerator Use();
}
public class SomeItem : MonoBehaviour, Item
{
// throws a compile time exception if SomeItem doesn't implement Use()
}