Search Unity

How to set Gameobject width in script as if it is done in Editor

Discussion in '2D' started by ScottAdams, Oct 1, 2021.

  1. ScottAdams

    ScottAdams

    Joined:
    Nov 23, 2016
    Posts:
    72
    I have a 2d game object used in the UI. It contains a Rect transform, canvas renderer and image

    I can change the width in the editor in the Rect transform for example from 200 to 100 and the width in scene in the editor is half as long. Great!

    I just can't seem to get it to work in script.

    The object is anchored to the left. min (0, 0.5) max (0, .5) and Pivot (0, .5) Scale is 1,1,1

    I have tried a number of ways in script and it just doesn't display properly. I have a percent I want to shrink the object by. Setting percentEarnedThisSeg to .5 for example doesn't give me an object half the original size.

    I can change the width value in the editor while the game is running and get exactly what I want. I just can't seem to do it in script.

    Here are some failed attempts:

    Code (CSharp):
    1.  
    2. // try 1
    3.  segment.transform.localScale = new Vector3(percentEarnedThisSeg, 1, 1);
    4.  
    5. // try 2
    6.  segment.rectTransform.sizeDelta *=  new Vector2(percentEarnedThisSeg, 1);
    7.  
    8. // try 3
    9.       var orgX = segment.rectTransform.rect.x;
    10.       var sizeDeltaX = orgX * percentEarnedThisSeg;
    11.       segment.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, sizeDeltaX);
     
    Last edited: Oct 1, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Manipulating RectTransforms in code is really hard, maddeningly so in fact.

    For instance, look at this code just to set anchors to the outside of the RectTranform itself. You'd think it would be one line but it is way more than a dozen.

    http://forum.unity3d.com/threads/sc...hor-to-gui-object-size-rect-transform.269690/

    The best approach I have found is to put other RectTransforms in the scene and copy their values out when you need them, but even that is perilous.
     
    ScottAdams likes this.
  3. ScottAdams

    ScottAdams

    Joined:
    Nov 23, 2016
    Posts:
    72
    Thanks! I was able to get it working. My "try 2" above was valid but I had an issue in another section of the code that made it look like it was failing. Your post though was useful and I learned something about setting the anchors
     
    Kurt-Dekker likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    So you know, the 2D sub-forum isn't about the UI system and there's a dedicated UI sub-forum here.
     
    ScottAdams likes this.
  5. ScottAdams

    ScottAdams

    Joined:
    Nov 23, 2016
    Posts:
    72
    My mistake! Thanks for the headsup!