OnGUI Button To Auto Position according to screen Resolution

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:

       if (GUI.RepeatButton (new Rect (leftcontrolright, leftcontrolup, leftcontrolxsize, leftcontrolysize), "move left")){
            Vector3 v3Force = thrust * -transform.right;
            rb.AddForce(v3Force);
        }

any idea how to do that?

Just out of curiousity, can you describe where the button is on the screen? :slight_smile:

Hi Methos5k,Its on bottom left corner…

So, then how you determine the bottom left position should be based on the screen height, I think, yes?

Note: with UGUI components, you can set anchors to corners :slight_smile:

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:

    Rect MR( float x, float y, float w, float h)
    {
        return new Rect (Screen.width * x, Screen.height * y, Screen.width * w, Screen.height * h);
    }

Then when you use it in OnGUI, to put a button in the lower right, you would do:

void OnGUI()
{
    if (GUI.Button( MR( 0.80f, 0.90f, 0.20f, 0.10f), "Button"))
    {
        // do your stuff
    }
}

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. :slight_smile: Meanwhile, you owe yourself to at least look at the new UI…