Search Unity

OnGUI Button To Auto Position according to screen Resolution

Discussion in 'Scripting' started by HBK_, Jan 13, 2018.

  1. HBK_

    HBK_

    Joined:
    Dec 1, 2017
    Posts:
    87
    Hi everyone,i have a Repeat Type OnGUI Button in a script and on unity's player it shows my button exactly where i wanted it to but on devices with other resolution it doesn't show the button where i placed it i wanna make my OnGUI Button to reposition itself on other devices with different resolution to that place where it was placed before.Here's the snippet of that button code:

    Code (CSharp):
    1.        if (GUI.RepeatButton (new Rect (leftcontrolright, leftcontrolup, leftcontrolxsize, leftcontrolysize), "move left")){
    2.             Vector3 v3Force = thrust * -transform.right;
    3.             rb.AddForce(v3Force);
    4.         }
    any idea how to do that?
     
    Last edited: Jan 14, 2018
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Just out of curiousity, can you describe where the button is on the screen? :)
     
  3. HBK_

    HBK_

    Joined:
    Dec 1, 2017
    Posts:
    87
    Hi Methos5k,Its on bottom left corner.....
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    So, then how you determine the bottom left position should be based on the screen height, I think, yes?
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Note: with UGUI components, you can set anchors to corners :)
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Like @methos5k points out, I would highly recommend using the "new" Unity GUI system (which is now four years old) instead of OnGUI().

    If you insist on using OnGUI(), I would make a handy rectangle-creation function like so:

    Code (csharp):
    1.     Rect MR( float x, float y, float w, float h)
    2.     {
    3.         return new Rect (Screen.width * x, Screen.height * y, Screen.width * w, Screen.height * h);
    4.     }
    5.  
    Then when you use it in OnGUI, to put a button in the lower right, you would do:

    Code (csharp):
    1. void OnGUI()
    2. {
    3.     if (GUI.Button( MR( 0.80f, 0.90f, 0.20f, 0.10f), "Button"))
    4.     {
    5.         // do your stuff
    6.     }
    7. }
    8.  
    In both X and Y directions the screen becomes addressible as 0.0f to 1.0f. That's how I do it when I use the old OnGUI() system. Upper left would be (0,0) and lower right would be (1,1) regardless of screen resolution.

    Aspect ratio may still be a concern however, but this is left as a mathematical exercise to the UI designer. :) Meanwhile, you owe yourself to at least look at the new UI...