I'm trying to create an interaction system for a game I'm developing with Unity and C# and I've been struggling with it for a while now. It consists of interactors and interactables. The idea is that interactors are responsible for initiating and finishing the interaction, and the interactables handle the actual interaction logic once it began. Each interactor can interact with a specific interactable and all interactables deriving from it.
There is some logic that all interactors share. Because of this I made a generic BaseInteractor
class that implements that logic (abstract class BaseInteractor<T> where T : BaseInteractable
). So now I can make e.g. grab interactor class like this: GrabInteractor : BaseInteractor<GrabInteractable>
. This works well but there is one issue - I would also like the BaseInteractable
to have a generic parameter which describes which interactor can interact with it. This is necessary because different interactables need to access different methods of the interactor (grab interactable needs to know the position and rotation of the interactor, while some other interactable might need to know the scale of the interactor).
However when the BaseInteractable
class has a generic parameter it creates a problem where I need to know the type of the interactable even in the BaseInteractor
class (abstract class BaseInteractor<T> where T : BaseInteractable<_what_to_put_here_>
). This is obviously a mess, but I can't figure out how can I design it better. I could obviously not inherit from the base classes at all, but then I would need to repeat the same code.
EDIT: One solution I thought of is to declare these classes like this: abstract class BaseInteractor<T> where T : BaseInteractable<T>
and abstract class BaseInteractable<T> where T : BaseInteractor<T>
which I thought makes sense, but the compiler wouldn't allow me to do it.