Search Unity

  1. Calling all beginners! Join the FPS Beginners Mods Challenge until December 13.
    Dismiss Notice
  2. It's Cyber Week at the Asset Store!
    Dismiss Notice

Setting boundaries for a created button.

Discussion in 'Scripting' started by javid07, Dec 23, 2018.

  1. javid07

    javid07

    Joined:
    Dec 5, 2018
    Posts:
    8
    Hello, I am making a game where a reaction spawns on the screen and you have to press it as fast as you can then the next one pops up, so on. I'm having issues figuring out how to keep the button off the edges of the screen. Im using Random.Range from 0 to Screen.width for the x axis and the height for the y axis because it needs to be random. I tried to parent the new button to a panel that is the desired size of the boundaries and that did nothing. Here's my code please help me keep the button off the edges. (designing for mobile)
    Code (CSharp):
    1.     public GameObject reactionPrefabList;
    2.     public float reactionSpawnTotal = 5;
    3.     private bool isClicked = false;
    4.     public Transform panel;
    5.     public Sprite reactionPrefabSprite;
    6.  
    7.     void Start()
    8.     {
    9.         StartCoroutine(LaunchReaction());
    10.     }
    11.  
    12.     IEnumerator LaunchReaction()
    13.     {
    14.  
    15.         for (int i = 0; i < reactionSpawnTotal; i++)
    16.         {
    17.  
    18.             float xPos = Random.Range(0, Screen.width);
    19.             float yPos = Random.Range(0, Screen.height);
    20.             Vector3 spawnPos = new Vector3(xPos, yPos, 0f);
    21.             DefaultControls.Resources uiResources = new DefaultControls.Resources();
    22.             uiResources.standard = reactionPrefabSprite;
    23.             GameObject reactionPrefab = DefaultControls.CreateButton(uiResources);
    24.             RectTransform rt = reactionPrefab.GetComponent<RectTransform>();
    25.             rt.sizeDelta = new Vector2(100, 100);
    26.             reactionPrefab.transform.SetParent(panel.transform, false);
    27.             reactionPrefab.transform.position = spawnPos;
    28.             yield return new WaitUntil(() => isClicked == true);
    29.         }
    30.     }
    31. }
     
  2. javid07

    javid07

    Joined:
    Dec 5, 2018
    Posts:
    8
  3. Nit_Ram

    Nit_Ram

    Joined:
    May 8, 2016
    Posts:
    7
    Last edited: Dec 23, 2018
    javid07 likes this.