Search Unity

What is a good way to initialise or refresh GUI panels?

Discussion in 'UGUI & TextMesh Pro' started by Kylotan, Sep 5, 2014.

  1. Kylotan

    Kylotan

    Joined:
    Feb 17, 2011
    Posts:
    212
    I have some complex UI which needs to pull data from the game and rebuild the layout on occasion. There are basically 4 times when this happens:
    1. At the beginning, because the panel begins as visible
    2. During play, when a disabled panel becomes enabled/visible for the first time
    3. During play, when a previously disabled panel becomes enabled/visible for the second or subsequent times
    4. During play, when the game state changes

    My dilemma is trying to find a clean way to handle all this. Assume I have the recalculation code handled in an UpdateGUI function - the issue is, where do I call it from?
    • If I call it from Start, that works fine for situation #1 and #2, but it won't trigger in situation #3 (as Start was already called), and I need to call it manually somehow in situation #4
    • If I call it from OnEnable, that works for situation #3, but not in #1 or #2 because there are connections that only get set up in Start which are necessary for polling the data, and Start doesn't get called immediately
    • If I just try and call UpdateGUI directly after enabling a panel, that doesn't work for situation #2 because Start won't have been called yet
    Maybe I can create some sort of external PanelManager which could make sure they all begin as enabled and have Start called, before hiding the currently unused ones. But that feels a bit messy too, and it would be annoying to have to do that for every panel that isn't visible all of the time.

    Anybody have any suggestions?
     
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    I'm not entirely sure if I understand correctly, but what about using Awake() to initialise everything for the first time?
     
  3. Kylotan

    Kylotan

    Joined:
    Feb 17, 2011
    Posts:
    212
    You can't really do much in Awake because various other objects may not exist yet.

    I expect I can hack around this whole problem with some sort of dirty flag system which gets checked in Update, but that's a pretty ugly solution.
     
  4. superpig

    superpig

    Drink more water! Unity Technologies

    Joined:
    Jan 16, 2011
    Posts:
    4,657
    I think the simple solution is probably to have "if(!_isSetup) SetupGUI();" at the beginning of UpdateGUI, but I recognise that it's not elegant.

    Kinda smells a bit like you've got some unclear dependencies between code modules, though - something bidirectional. It should be possible to pin down the order of events such that e.g. game state changes that cause UpdateGUI to be called don't begin happening until all the UI has been initialized.