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.
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.
Floor prefab consists of 2 prefabs: “top” and “bottom”.
[21217-ekran+alıntısı.png|21217]
What I wanted to achieve was:
[21216-ekran+alıntısı.png|21216]
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.