Calling a generic function from script

Hi,

I have created a window class that allows to display content in a typical window-style context. Now that I have this, I’d like to add generic content to it. Given that I have my windows.cs attached to a GameObject, I would like to define a public variable that is only linked to a specific content. This needs to be highly dynamic, which is why I cannot use the (too specific) GetComponent call syntax.

Example of what I’m trying to achieve:

public class Window : MonoBehaviour {
    public GameObject contentScript;
    void ShowWindow() {
        //create window etc
        contentScript.Content()
    }
}

public class RandomContent : MonoBehaviour {
    public void Content() {
        GUILayout.BeginHorizontal();
        GUILayout.Label("Bleh");
        GUILayout.EndHorizontal();
    }
}

If I was to use GetComponent, I would have to pre-define the class of the Content() function each time, which would render the whole window system obsolete, since the point is to be dynamic enough to avoid hardcoded definitions.

Does that make sense? Anyone a good idea how to cope with that? Thanks

Sounds to me like you should define a base class with a virtual method for the content - then you can use GetComponent with the base class and use that.

 public class ContentBase : MonoBehaviour
 {
      public virtual void Content() {}
 }

 public class ContentType : ContentBase
 {
      public override void Content() 
      {
          GUILayout.Label("Some Label");
      }
 }

 public class SomeContentUser : MonoBehaviour
 {
        void OnGUI()
        {
             foreach(var contentItem in GetComponentsInChildren<ContentBase>())
             {
                 contentItem.Content();
             }
        }
 }