I have attached a script that creates a building object with a model and a collider on different spots of the terrain in runtime.
The buldings are created, but I stilll can’t get them to be at the same height as the terrain they have underneath. The terrain is not flat, so they should each have different height. However, all buildings end up with the same height, so some are floating and some are halfway undergound.
The script that I have attached to each building is the following:
private float houseHeight;
GameObject house;
RaycastHit hit;
void HouseHeight()
{
house = gameObject;
Debug.Log("building: " + house.name);
Vector3 groundzero = new Vector3(house.transform.position.x, 2000f, house.transform.position.z);
Ray downRay = new Ray(groundzero, Vector3.down);
if (Physics.Raycast(downRay, out hit))
{
houseHeight = 2000f - hit.distance;
house.transform.position = new Vector3(house.transform.position.x, houseHeight, house.transform.position.z);
Debug.Log("houseHeight: " + houseHeight);
Debug.Log("hit.distance: " + hit.distance);
}
I added the Logs so I would know what was happening. It seems the building name is changing, so each script knows it’s attacked to a different object. But hit.distance is always the same, and houseHeight too. What am I missing?
Thanks for your help.