Search Unity

Making overlay UI element scale with camera and resolution?

Discussion in 'Scripting' started by jpthek9, Oct 8, 2015.

  1. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    For example, for a health bar that follows an object, how would I make the healthbar maintain a constant size relative to the world-space object it's following? So when the camera zooms out or in, or the resolution changes, the health bar appears to be only as wide as the object it's following.
     
  2. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92


    These settings on the UI Canvas, works for me in the terms of UI size and resolution changes. The thing is, the UI will always be in front of the camera and keep a distance of 1 unit. But the UI will still be the same when the camera zooms in or out which is bad since you want it to be object specific.

    One thing that comes in my mind is to write a script that would adjust the Plane Distance value on the Canvas component according to the distance between camera and the object itself, so if the camera zooms in or out ( by moving physically ) you would change this plane distance value by the help of a multiplier variable that you'd set in inspector, thus you can keep the UI's size in the same amount whereever the camera's position is. The resolution part, as I said, will be handled by the Canvas Scaler component, go have a look at the reference page to see what would be the best settings for your target resolutions. Also last thing to say, UI's scale wont change if you zoom in / out your camera using field of view.
     
    jpthek9 likes this.
  3. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    Thanks for your suggestion. I'll play around with canvas scaler and see if there's a setting that will keep UI elements the same size.
     
  4. jpthek9

    jpthek9

    Joined:
    Nov 28, 2013
    Posts:
    944
    Works like a charm :D. Setting Screen Match Mode to Shrink solves the problem. That, and multiplying the element's scale by (targetCameraHeight / camera.transform.position.y).
     
  5. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    Happy to hear that ! But be careful though, if you set to Shrink :

    ( Ref )

    So if your game will be played on the devices which may have higher resolution than your reference res. that you set on the inspector, UI won't be scaled and will look smaller than it should be. Match for an optimal result, you can set it to Match Width or Height and adjust the value as 0.5. But anyways, just try them for yourself eventually you will find the best settings, cheers!
     
    jpthek9 likes this.