- Home /
2D Get Object Height to stack up on the screen
I'm trying to get these objects in a line connected to each other but it's not working out too well.
void StackUp()
{
tempHolder = new GameObject("Holder").transform;
tempHolder.SetParent(boardHolder);
GameObject instance;
for (int y = startPos; y < endPos; y++)
{
GameObject toInstantiate = lineTiles[Random.Range(0, lineTiles.Length)];
instance = Instantiate(toInstantiate, new Vector3 (0, currentPos, 0f), Quaternion.identity) as GameObject;
currentPos += (float)instance.GetComponent<Collider2D>().bounds.size.y;
instance.transform.SetParent(tempHolder);
}
}
The objects in lineTiles are different sizes in height and width.
I can't seem to get them to stay connected though. I think it would have to do with currentPos but no idea what I'm doing wrong to get it like this:
There are also some objects hidden under each other:
Answer by toromano · Oct 19, 2015 at 01:28 PM
You should consider each gameobject size and center separately:
for (int y = startPos; y < endPos; y++)
{
float currentPos = .0f;
GameObject toInstantiate = lineTiles[Random.Range(0, lineTiles.Length)];
instance = Instantiate(toInstantiate, new Vector3 (0, currentPos, 0f), Quaternion.identity) as GameObject;
float size = (float)instance.GetComponent<Collider2D>().bounds.size.y;
instance.transform.position = new Vector3(0,currentPos + size/2,0); // center position of the gameobject
currentPos += size; //up position of the gameobject
instance.transform.SetParent(tempHolder);
}
I had to remove the currentPos reset out the loop ;) but that was it thank you! I think I just had a really bad understanding of how the size.y was handled and this cleared it up thanks!
Your answer
Follow this Question
Related Questions
Cant change transform.position of gameobject 1 Answer
XBox Controller Angle of Fire Incorrect 0 Answers
2D Array of GameObjects... 1 Answer
Accessing game object based on position 2 Answers