- Home /
Changing an image size cancels its anchoring?
I have a 2D game in which I have a simple UI image of a rectangle that is anchored to the middle right.
In my script, I'm changing the image's size like so:
RectTransform objectRectTransform_bar_bg = bar_bg.GetComponent< RectTransform >();
objectRectTransform_bar_bg.sizeDelta = new Vector2(Screen.width, Screen.height / 2.35f);
When I run my game, and the image's width changes, it seems like the anchor does'nt work any more and the image shifts to the left instead of remaining locked to the right side. When I change the image's width using the editor (not via script), it works and the image stays locked on the right side.
What can cause this? Am I doing something wrong?
Answer by TreyH · Jun 24, 2019 at 02:17 PM
There's a function for this btw: RectTransform.SetSizeWithCurrentAnchors
var newSize = new Vector2(Screen.width, Screen.height / 2.35f);
objectRectTransform_bar_bg.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, newSize.x);
objectRectTransform_bar_bg.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, newSize.y);
Your answer
![](https://koobas.hobune.stream/wayback/20220612203736im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
RectTransform sizeDelta not really working 0 Answers
How to copy one Rect Transform data to other Rect Transform 2 Answers
2D game using sprites. 1 Answer
How to create 3D game object in specified pixel size? 2 Answers
[Closed]2D image as an object 3 Answers