Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. We are looking for feedback on the experimental Unity Safe Mode which is aiming to help you resolve compilation errors faster during project startup.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

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:
    207
    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:
    207
    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 :)
     
  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:
    207
    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.
     
unityunity