In my Unity scene, I have a couple of
spriteRenderers and a
thisButton. The spriteRenderers are spread horizontally across my scene. I want to change the button width to span from the leftmost spriteRenderer to the rightmost spriteRenderer.
To do this, I have subtracted the x-Coordinate of the rightmost spriteRenderer (
fRightEndingPosition) from the x-Coordinate of the leftmost spriteRenderer (
float fLeftStartingPosition = leftmostSpriteRenderer.transform.position.x; float fRightEndingPosition = rightmostSpriteRenderer.transform.position.x; float fButtonTargetWidth = fRightEndingPosition - fLeftStartingPosition;
Then, I try to set the width of
thisButton to the value of
fButtonTargetWidth by doing
RectTransform buttonSize = thisButton.GetComponent<RectTransform>(); buttonSize.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fButtonTargetWidth);
However, when I try to use this as the width of my button, the result is not correct. I am pretty sure this has something to do with different types of coordinates being used for the spriteRenderers and the button (world, screen, viewport, etc.), but I haven't been able to figure this out on my own.
In one specific example
1.1. In my scene, a button that spans this distance has a width of roundabout 40 on its RectTransform. So clearly, setting the width of this RectTransform (
2.2) in code results in a button that is way to narrow. In fact, after setting it's width to 2.2, it is not visible at all.
How do I transform this distance of 2.2 to the desired width of roundabout 40, in a way that this distance would be transformed correctly, no matter what the actual value of fButtonTargetWidth is?