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.
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 You!!! That made them spawn in random x,y coordinates … the only thing now is making it appear with the Sprite background instead of being empty with a text box…
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);
}
}