- Home /
 
How to instantiate a gameobject by aligning it to another one
Hello. I'm new in Unity3D. I'm developing a top-down game (2D Game). I have a floor prefab and I want to instantiate it, but its spawn position in YAxis has to be upper edge of previous floor prefab.
What I want to achieve is: For example, I want to construct a 5 floors building.
Here's my GameSrarter script.
using UnityEngine; using System.Collections;
public class GameStarter : MonoBehaviour {
 void Awake(){
     // First prefab is instantiated Vector2.zero position.
     GameObject floor1 = Instantiate(Resources.Load("Prefabs/floor"), Vector2.zero, Quaternion.identity) as GameObject;
     // But I cannot find upper edge of floor1 prefab as Vector.
     GameObject floor2 = Instantiate(Resources.Load("Prefabs/floor"), IDontKnowHowToSpecifyThisOne, Quaternion.identity) as GameObject;
 }
 
               }
Thanks for your helps.
Could you use floor1.transform.position.y + 2 (or some # that works for what you are trying to do)
I tried it. But floor heights might change. I have to find the exact vector position for the next floor that will be placed at top of the previous floor.
Answer by ahmetegesel · Jan 27, 2014 at 03:17 PM
Floor prefab consists of 2 prefabs: "top" and "bottom".

What I wanted to achieve was: 
 void Awake(){
         float nextPosition = Vector2.zero.y;
         for (int i = 0; i < 5; i++) {
             GameObject floor = Instantiate(Resources.Load("Prefabs/Environment/floor"), new Vector2(Vector2.zero.x, nextPosition), Quaternion.identity) as GameObject;
             Transform floorTop = floor.transform.FindChild("top");
             Transform floorBottom = floor.transform.FindChild("bottom");
             float halfBottom = (floorBottom.renderer.bounds.size.y / 2);
             float halfTop = (floorTop.renderer.bounds.size.y / 2);
             nextPosition += ((floorTop.position - floorBottom.position).y) + halfTop + halfBottom;
         }
     }
 
               This code works for me but If anyone knows such efficient way that make this code simple, Please answer.
Thank you.
Answer by Kiloblargh · Jan 25, 2014 at 08:04 PM
Presumably your floor prefabs are all different heights? (If not- duh!) So, maybe you want a
 howHigh :    Dictionary.< GameObject, float >
 
               That keeps track of the height of all floors prefabs. And a
 heightSoFar : float 
 
               that is set to zero with each new building, and increased by the appropriate floor height ( howHigh[floor1] ) etc. each time you add a floor to the building. 
How can I find height of the floor and use it to deter$$anonymous$$e start positiom of next floor prefab?
Your answer