Home > Enterprise >  Object doesn't teleport according to the random range limits
Object doesn't teleport according to the random range limits

Time:07-18

I tried making a button to teleport somewhere on a map when I press it, I used Transform.Position() and Random.Range() to teleport the button on the x and y axis.

The expected result was that the button will teleport somewhere between (800, 350) and (-800, -350) because those are the numbers I put in the Random.Range(). But somehow the button sometimes teleports as y < -350 and x < -800. the button also never has a positive x or y position.

I even tried to make the range only positive and 0, but the button is still on negative x and y position(HOW?). I have code here below can someone tell me what is wrong?

Unity itself doesn't show any error.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class OnClick : MonoBehaviour
{
    public Text scoreText;
    public int score = 0;
    public void Teleport()
    {
        score  = 1;
        transform.position = new Vector2(Random.Range(-800, 800), Random.Range(-350, 350));
        scoreText.text = "Score: "   score;
    }
}

CodePudding user response:

I guess the button is a child object. If so then what you are looking at as position in the editor is the local position but what you set with the code is the world position. Putting the higher-level objects on (0,0,0) will make the local and world position the same for this object.

CodePudding user response:

For a UI element positioning, make sure to set the object's anchor correctly.

  • Related