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

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:

// try 1
 segment.transform.localScale = new Vector3(percentEarnedThisSeg, 1, 1);

// try 2
 segment.rectTransform.sizeDelta *=  new Vector2(percentEarnedThisSeg, 1);

// try 3
      var orgX = segment.rectTransform.rect.x;
      var sizeDeltaX = orgX * percentEarnedThisSeg;
      segment.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, sizeDeltaX);

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.

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.

1 Like

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

1 Like

So you know, the 2D sub-forum isn’t about the UI system and there’s a dedicated UI sub-forum here.

1 Like

My mistake! Thanks for the headsup!