Unity UI can be hard
Mon 30/09/2019
Rect Transforms
Unity has many transforms that you use for game objects; however, Unity uses the RectTransform for UI. There are many things you can do: set Anchors and Pivots.

ScreenWidth
I've used Screen.width before to get the width of the screen and set a variable to the width of the screen. Sometimes, this won't work 'causing all the UI elements to . So, you gotta get creative.
Say you have a button that's not playing nicely. You can create an empty gameObject in the canvas and call it ButtonParent. Put the Button in the ButtonParent like below.

In your code, you want to create a RectTransform variable and in editor, drag the ButtonParent to reference it as the parentRectTransform.
Next, instead of using, Screen.width as your width, use parentRectTransform.rect.width.
using UnityEngine;
public class ButtonTest : MonoBehaviour {
[SerializeField] private RectTransform parentRectTransform;
void Start() {
float screenWidth = parentRectTransform.rect.width;
// int screenWidth = Screen.width;
}
}
Last updated
Was this helpful?