Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Random button position on press

Discussion in '2D' started by PatD17th, May 26, 2021.

  1. PatD17th

    PatD17th

    Joined:
    Mar 27, 2013
    Posts:
    14
    Hello,
    So my script looks like this (below) and the problem is that the button goes off the screen despite its position being limited by the numbers written in the code. The max X and Y is set to 50 and somehow after the click it goes to even -+500 or more. What am I doing wrong?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class RandomPosition : MonoBehaviour
    7. {
    8.     public int xPos;
    9.     public int yPos;
    10.     public GameObject InteractiveObject;
    11.  
    12.  
    13.     void Update()
    14.     {
    15.         if (Input.GetMouseButtonDown(0))
    16.         {
    17.             xPos = Random.Range(0, 50);
    18.             yPos = Random.Range(0, 50);
    19.             InteractiveObject.transform.position = new Vector2(xPos, yPos);
    20.         }
    21.     }
    22. }
    23.  
     
  2. PatD17th

    PatD17th

    Joined:
    Mar 27, 2013
    Posts:
    14
    These are my Object coordinates
    upload_2021-5-26_19-40-19.png
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    Please note that you'll get quicker results if you post UI questions on the UI forum rather than the 2D one.
     
  4. PatD17th

    PatD17th

    Joined:
    Mar 27, 2013
    Posts:
    14
    I see that it's sticking to the corner of the canvas
     

    Attached Files: