How to instantiate UI elements centered around an empty object
Hi,
I'm pretty new to unity and I'm making a word game, the player has to fill the blank. Now, I'm trying to make the word be divided into different panels, one panel for each letter, and I want them to instantiate centered around an empty object. This is the code I have so far : //------------------------------------------------------Cube placement------------------------------------------------
for (int x = 0; x < gridX; x++)
{
Vector3 pos = new Vector3(wordPanel.transform.position.x, 0, wordPanel.transform.position.y) * spacing;
cube = Instantiate(letterPanel, pos, Quaternion.identity) as GameObject;
cube.transform.SetParent(wordPanel.transform, false);
}
The problem is that they all instantiate at the center, on top of each other. I was looking for something like this :
Any ideas ?
Answer by Dibbie · Apr 05, 2016 at 12:31 AM
Track the position of the last instantiated cube, and have it spawn at that location + the width of the cube your trying to spawn, and thatll kind of get it linked side by side. So, to modify your code:
public Transform lastCubeLocation;
for (int x = 0; x < gridX; x++)
{
Vector3 pos = new Vector3(wordPanel.transform.position.x + lastCubeLocation, 0, wordPanel.transform.position.y) * spacing;
cube = Instantiate(letterPanel, pos, Quaternion.identity) as GameObject;
cube.transform.SetParent(wordPanel.transform, false);
lastCubeLocation = cube.transform;
}
At this point, since its already spawning ontop of eachother, it will add the last cubes location, if the cubes are (or will be) different sizes, youll have to also add cube.rectTransform.width to the location it is being spawned as well, to ensure they are beside eachother and not overlapping - this is also pseudo code, im not looking at an editor right now, but concept is there, that should work for you.
Hey! Thank you very much for the feedback, you got me on the right track.After some further research I solved it by using a Horizontal Layout Group, which pretty much does it on its own...