@OlivierRigel
hi there,
Your instantiate has a cast twice, don’t know if that mattered.
I wrote some example code.
I’m pretty noob but have already wasted good amount of time learning Unity…
Manual can be bit hard, it’s like you described…
Better check official Unity video tutorials…
Below I pasted some examples how to instantiate, move, rotate, scale and resize UI items.
NOTE:
I typed the structPanel as RectTransform, but it’s not shown here.
And I also cut away your for loop details.
NOTE 2:
It’s also worth noting that it matters quite a lot how you setup your UI elements - if you want to have sprite like behaviour, first inspect / set your pivot and stretching. Place your UI element on canvas, then change pivot to be center or left bottom for example, what makes the calculations of positions easier for you later…
Also, sprites are most like better used as “elements” some make them non-stretchy, by picking centered anchors… If you make elements stretched then you are basically calculating distance to parent RectTransforms edges, not actual size of your sprite like I did here…
for (int i = 0 ; i < 10; i++)
{
if (strVisible)
{
// Instantiate
GameObject buttonS = Instantiate(prefabStruct) as GameObject;
// Parentation
buttonS.transform.SetParent(structPanel, false);
// Get rectTransform of UI item
RectTransform brt = buttonS.GetComponent<RectTransform>();
// Add some random offset to UI item
brt.localPosition = brt.localPosition +
new Vector3(Random.Range(-distance, distance),
Random.Range(-distance, distance));
// Add random rotation around z as deg
brt.rotation = Quaternion.Euler(0f, 0f, Random.Range(-180f, 180f));
// Add random ~scaling~ between 1-1.5
float s = Random.Range(1f, 1.3f);
// Most likely don't want to do this, scaled UI item might not be good idea
//brt.localScale = new Vector3(s, s, s);
// Change dimensions instead you probably want to do this
//if not animating size - offset to current size
brt.sizeDelta = new Vector2(brt.sizeDelta.x * s, brt.sizeDelta.y * s);
}
}