I’ve been working on this for hours and cannot figure it out. I’m trying to change the position if my UI Button, but every-time I do, my button ends up somewhere waaaaaay across the screen (not the coordinates I put in).
I’m changing the position of my button through script so it randomly picks a new location every 2 seconds.
Here’s my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomMove : MonoBehaviour
{
public Vector3[] positions;
private float nextActionTime = 0.0f;
public float period;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (Time.time > nextActionTime)
{
nextActionTime += period;
int randomNumber = Random.Range(0, positions.Length);
transform.position = positions[randomNumber];
}
}
}
I’m setting the coordinates in the inspector window (since it’s a public var), and my current starting position of the button is x.782 y.-368 z.-3. When I type in a location for my button to go (using my script) which is just raising the Y position up slightly, it sends my button somewhere completely off screen, way away from my game scene. Is there a reason why it’s doing this?
Any help would be great…thanks all.
@vakabaka is pretty much right, use RectTransform instead.
“Is there a reason why it’s doing this?”
To me it sounds you really have to work through all the UI basics tutorials / read manual to get a grip how the whole system actually works. You first have to understand how RectTransform works, how Canvas coordinates work, and how Canvas can be sized using various methods.
Your UI elements are in Canvas / unless you are using some old IMGUI elements… So first thing would be to make your canvas have certain size, so it doesn’t change it’s pixel resolution by current screen size for example. Screen size can be anything but canvas should have some specific dimensions. So set CanvasScaler’s UI Scale Mode to “Scale with Screen Size” and set the Reference Resolution to something useful.
For example, say you had 800x400 resolution, then you can just place your UI element to random positions like this. First you’d have to get half dimensions of your Canvas Rect (as you move from center to left or right edge and so on):
Then you can create some method you call on button click… this will offset your button’s RectTransform. Note that button should be parented under Canvas directly, so the localPosition will work properly.
var posX = Random.Range(-canvasHalfW, canvasHalfW);
var posY = Random.Range(-canvasHalfH, canvasHalfH);
// position in parent space
buttonRt.localPosition = new Vector2(posX,posY);
With this, your button can be placed anywhere between x -400 and 400, and in y -200 and 200. These numbers will only make sense in Canvas RectTransform’s Rect dimensions.