Yes, an interface is one way to do this. You can use GetComponents
(note the additional s
) to get all components on a gameObject which implement the same interface or inherit from the same class.
So you can create an interface, let's call it IContextOptionsProvider
, with a method IEnumerable<ContextOption> GetContextOptions()
(assuming ContextOption
is a plain old C# class you created to represent a context option). Then, when you create a MonoBehaviour which is supposed to add one or more context menu options to the gameObject it is on, you have it implement that interface and implement that method to return the context options.
Now if you want to get all the context options of all the components of a GameObject which implement IContextOptionsProvider
, you can do it like this:
foreach(IContextOptionProvider provider in gameObject.GetComponents<IContextOptionProvider>()) {
foreach(ContextOption contextOption in provider.GetContextOptions()) {
// do what needs to be done with each contextOption
}
}