Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Can I make this general UIList solution more flexible?

Discussion in 'UGUI & TextMesh Pro' started by andreaswitzen, Aug 22, 2021.

  1. andreaswitzen


    Apr 25, 2020

    I'm trying to write a library of reusable UI classes to allow for faster prototyping of more complex UI. To start with I have two classes, UIInspector and UIElement.

    UIInspector stores a reference to a game object "focusObject", and a "onChange" unity event. UIElement finds the nearest UIInspector on Awake, either on the same game object or in its parents and throws an error if it doesn't find one, and references the focusObject of this inspector. I then have things like stat labels that show the value of a certain stat in a game object and tooltips inherit from UIElement so that I can just drag and drop a prefab label like this to for instance a panel that has an inspector and have things work without having to write any additional script.

    Then I have a UIList class that looks like this:

    Code (CSharp):
    1.     public class UIList : UIElement
    2.     {
    3.         public GameObject listItemPrefab;
    5.         private List<GameObject> objectList = new List<GameObject>();
    7.         public void SetList(List<GameObject> objectList)
    8.         {
    9.             this.objectList = objectList;
    10.         }
    12.         public override void Refresh()
    13.         {
    14.             if (listItemPrefab) {
    16.                 foreach (Transform child in transform) {
    17.                     Destroy(child.gameObject);
    18.                 }
    20.                 foreach (GameObject listObject in objectList) {
    21.                     GameObject item = Instantiate(listItemPrefab, transform);
    22.                     if (item.TryGetComponent(out UIInspector itemInspector)) {
    23.                         itemInspector.focusObject = listObject;
    24.                         itemInspector.onChange.Invoke();
    25.                     }
    26.                 }
    27.             }
    28.         }
    29.     }
    This works well except for one very small problem. To set the list of objects to show UI for I need to write a custom UIInspector and call SetList() from there. Is there any solutions to this that would allow me to set this up in the editor without writing any additional script?
    Last edited: Aug 22, 2021