I’m new to Unity and coding in general and have been trying to move a UI element to the right side of the screen via a button. I don’t know how to write a script that would move the UI element as I have never done it before.
First question: which UI system are you using? Hopefully it’s the UnityUI (Canvas-based) system, I’ll answer under that assumption. (If you’re using the OnGUI-based system, I recommend finding a newer tutorial)
In UnityUI, a UI element can be moved like any other object, by setting its position. The only real difference is that UI elements use RectTransform, a derived class from the regular Transform, and therefore not all of their positioning control is accessible unless you access it as a RectTransform.
So on a plain old GameObject in the scene, you might move the object like:
public Vector3 newPosition = new Vector3(1f,2f,3f);
void Start() {
transform.position = newPosition;
}
This will work on a RectTransform, but you might want to use the RectTransform properties more directly so you have more control. So that might look like:
public Vector3 newPosition = new Vector3(1f, 2f, 0f);
void Start() {
RectTransform rectTransform = (RectTransform)transform;
rectTransform.anchoredPosition = newPosition;
}
When you go through rectTransform, you have access to all sorts of new values (anchorMin, anchorMax, sizeDelta, etc) that give you much more precise control over the element’s position than you’d have by just setting transform.position.