marijnz / unity-toolbar-extender

Extend the Unity Toolbar with your own Editor UI code.
MIT License
1.67k stars 168 forks source link

Manually repaint on demand? #32

Closed Barina closed 1 year ago

Barina commented 2 years ago

Hi, love this asset! Is there a way to force a repaint? to let's say show a timer. I didn't find any. I can register a callback on EditorApplication.update but I didn't find what to call..

Barina commented 2 years ago

Alright I assumed UnityEditor.Toolbar derives from some Editor so I tried to get a Repaint method and it worked. My solution:

[InitializeOnLoad]
class MyClass
{
    static Action toolbarRepaint;

    public MyClass()
    {
        EditorApplication.update += TryRepaintToolbar;
    }

    static void TryRepaintToolbar()
    {
        if (toolbarRepaint != null)
        {
            toolbarRepaint();
            return;
        }

        Type t = typeof(Editor).Assembly.GetType("UnityEditor.Toolbar");
        var tbs = Resources.FindObjectsOfTypeAll(t);

        for (int i = 0; i < tbs.Length; i++)
        {
            UnityEngine.Object tb = tbs[i];
            if (tb.GetType() == t)
            {
                toolbarRepaint = (Action)t.GetMethod("Repaint")?.CreateDelegate(typeof(Action), tb);
                return;
            }
        }
    }
}

This will seek for the first UnityEditor.Toolbar it can find and creates and caches an System.Action delegate and invokes it on every EditorApplication.update. You probably want to unregister when not needed.