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 'UGUI & TextMesh Pro' 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. public class RandomPosition : MonoBehaviour
    6. {
    7.     public int xPos;
    8.     public int yPos;
    9.     public GameObject InteractiveObject;
    10.     void Update()
    11.     {
    12.         if (Input.GetMouseButtonDown(0))
    13.         {
    14.             xPos = Random.Range(0, 50);
    15.             yPos = Random.Range(0, 50);
    16.             InteractiveObject.transform.position = new Vector2(xPos, yPos);
    17.         }
    18.     }
    19. }
    20.  
    Object coordinates, original object position is in the middle of the screen.


    Somehow its sticking into the canvas corner.
     
  2. PatD17th

    PatD17th

    Joined:
    Mar 27, 2013
    Posts:
    14
    No one to help?