Search Unity

Callback when a ui element is going to be rendered

Discussion in 'Scripting' started by Zenix, Jun 20, 2017.

  1. Zenix

    Zenix

    Joined:
    Nov 9, 2009
    Posts:
    213
    Is there a callback that's fired before a ui element is rendered? I'd like to adjust the elements position just before rendering.

    OnWillRenderObject would be great, but it only works for non ui elements.
     
  2. Scabbage

    Scabbage

    Joined:
    Dec 11, 2014
    Posts:
    268
    There any reason for not just using Update/LateUpdate? That's in step with the actual frames of the game, so no matter what, it'll always be called before a frame is rendered.

    Otherwise, is OnGUI what you're looking for?
     
  3. Zenix

    Zenix

    Joined:
    Nov 9, 2009
    Posts:
    213
    I need to snap ui elements to integer positions. I found an example of someone doing this with OnWillRenderObject and OnRenderObject, which seemed nice and straightfoward until I found Unity doesn't fire OnWillRenderObject for canvas objects. It requires two callbacks so you can move the element back to it's original postion after being rendered.
    Doing this sort of thing in Update will mess up the positions of everything.

    OnGUI is horrible and should not be used for anything :)
     
    CloudyVR likes this.
  4. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    I wonder if a shader would be a better solution for this?
     
  5. Zenix

    Zenix

    Joined:
    Nov 9, 2009
    Posts:
    213
    Yeah, you're probably right. I know Unity's sprite shader has a 'pixel snap' option but it doesn't work for me. Will look at implementing my own shader based solution.
     
  6. Scabbage

    Scabbage

    Joined:
    Dec 11, 2014
    Posts:
    268
    So sorry for the semi-necro, but it's only been a week so whatever.

    I've just come across some old code in one of my projects that uses OnPostRender. It's been a long time since I wrote it so it never even occured to me. After a look at the documentation there's also OnPreRender. If you haven't gone the shader method (or found these already by now), those might be what you want.