I have found multiple “solutions” to this problem, however none of them work. Whether this is because the solutions are outdated or the solutions I found don’t fit for my problem, I don’t know. I am using this c# script to instantiate ten instances of a GUI button, all in random colors, sizes, and positions. I have a base version of the GUI button I want to instantiate as a prefab in my assets and that is what I am instantiating in the script:
for (int i = 0; i < 10; i++)
{
colorSetter = Random.Range (Random.Range (Random.Range (1, 2), Random.Range (3, 4)), Random.Range (Random.Range (5, 6), Random.Range (7, 8)));
size = Random.Range (1, 3);
circle.gameObject.transform.localScale = new Vector2 (size, size);
if (colorSetter == 1)
{
circle.image.color = blue;
}
if (colorSetter == 2)
{
circle.image.color = red;
}
if (colorSetter == 3)
{
circle.image.color = green;
}
if (colorSetter == 4)
{
circle.image.color = grey;
}
if (colorSetter == 5)
{
circle.image.color = pink;
}
if (colorSetter == 6)
{
circle.image.color = yellow;
}
if (colorSetter == 7)
{
circle.image.color = cyan;
}
if (colorSetter == 8)
{
circle.image.color = purple;
}
Instantiate(circle, new Vector2(Random.Range(0, 500), Random.Range(0, 750)), Quaternion.identity);
}
This script works beautifully, just like I want it to. However it instantiates the object in the top of the hierarchy. This forms issues however because the objects I’m instantiating are GUI elements and they MUST be a child of the canvas.
I cannot seem to figure out how to get these objects to instantiate as a child of the canvas. any help will be greatly appreciated.