Trying to create 10 buttons in random positions from script

The code that I have creates 10 buttons but they are all empty and right on top of each other in the center of the screen with only a text box showing… I would like to use this Shrimp Sprite that I have for the backgrounds which is placed in the initial button that I use to attach this script to (which continues to display as the shrimp and moves to a random spot when I run it) but the other new buttons are empty and spawn right in the center of the screen.

void Start()
{
    for (x = 0; x <= 10; x++) {

    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    var ShrimpSprite = Resources.Load<Sprite>("shrimp");
    uiResources.standard = ShrimpSprite;
   

    GameObject uiButton = DefaultControls.CreateButton(uiResources);
    uiButton.GetComponent<Sprite>();

    uiButton.transform.SetParent(canvas.transform, false);
    transform.Translate(rnd.Next(-100, 100), rnd.Next(-100, 100), 0);
    Debug.Log("button " + x);

    }
}

I see in line 14 you have hard-wired magic numbers of -100 and 100 for x and y.

Are those values reasonable given the size of your canvas, plus the scale mode of your canvas? Or are those numbers so small they are not deflected enough from center?

Run the code, then look in the inspector at the RectTransform values on each button. are the reasonably different?

You can look at the CanvasScaler to dynamically adjust your values if need be.

Thank, I’ll check it out here… I just put those coordinate in for testing so they wouldn’t be scattered everywhere (hopefully lol)

The Rect Transform values of the new buttons are all 0,0,0

Start debugging the rnd function then… is it returning zero?

Next try putting constant nonzero values in… do they stick?

etc. etc. Chase the data down.

ALSO… you wrote:

transform.Translate(rnd....)

Don’t you actually mean

uiButton.transform.Translate(rnd....)

:slight_smile:

Thank You!!! That made them spawn in random x,y coordinates :slight_smile: … the only thing now is making it appear with the Sprite background instead of being empty with a text box…

This is the full code btw if it helps…

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class SpawnTenShrimpButtons : MonoBehaviour
{

public GameObject canvas;
int x;
public System.Random rnd = new System.Random();


void Start()
{
    for (x = 0; x <= 10; x++) {

    DefaultControls.Resources uiResources = new DefaultControls.Resources();
    var ShrimpSprite = Resources.Load<Sprite>("shrimp");
    uiResources.standard = ShrimpSprite;

    GameObject uiButton = DefaultControls.CreateButton(uiResources);
    uiButton.transform.GetComponent<Sprite>();

    uiButton.transform.SetParent(canvas.transform, false);
    uiButton.transform.Translate(rnd.Next(-100, 100), rnd.Next(-100, 100), 0);

    }
}