Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Change Button Height/Width In code

Discussion in 'Scripting' started by GoodNight9, Apr 2, 2021.

  1. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    Hello! I'm trying to set a button's height and width in code so it scales in proportion to the screen size. But, I can't find the code to control it.
    with a 'Button' variable named 'myButton'
    The x and y position work : myButton.transform.position = new Vector3 (x,y,z);
    But I can't find myButton.width, or myButton.height. Nothing seems to access those variables :(
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    GoodNight9 and SparrowGS like this.
  3. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    Hi Praetor-!
    I've have actually been reading a lot and going through the documentation. The Built in Canvas stuff has been incredibly useful.

    I just want the insurance of knowing how to manually set a button on the screen to a ratio'd width and height in the case the canvas auto-size stuff puts buttons to close together. I'd like to make sure a few buttons never overlap on all screen ratios and resolutions.
     
  4. seejayjames

    seejayjames

    Joined:
    Jan 28, 2013
    Posts:
    685
    Get the RectTransform and then set the .localScale property. I avoid setting width and height because scale will also scale any child objects.

    yourRectTransform.localScale = new Vector3(buttonScaleX, buttonScaleY, 1); // Z value is irrelevant with UI


    You *can* set width and height with .sizeDelta though.
     
    GoodNight9 and SparrowGS like this.
  5. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Like @seejayjames said, width is sizeDelta.x and height is sizeDelta.y (assuming your object isn't rotated), if you want to do what you said manually you'll need to have 2 variables for how much of the screen resolution it takes and 2 variables for where it is along the screen resolution.

    No reason to actually do that though - just use the canvas scaling!
     
    GoodNight9 likes this.
  6. GoodNight9

    GoodNight9

    Joined:
    Dec 29, 2013
    Posts:
    123
    Thank you!!! I believe my question has been answered :)