- Object: HouseBuilder
- Object: housePrefab
The HouseBuilder places houses (currently just Unity cubes) on a layered world (as shown below). Whenever a house is not colliding with its chosen level in the world OR when it’s colliding with a tree, other house or any other level, then it should be destroyed.
Now it works kind of properly, but sometimes, when a house is actually colliding with a wrong level of the world, it is not being destroyed. But if I move the object just a little around in the scene view while the game is running it gets destroyed as well. (The collision with trees and other houses seems to be working as intended)
This script places houses until the limit of houses in the world is reached
public class HouseBuilder : MonoBehaviour
{
string[] mapLevels =
{
"Level01",
"Level02",
"Level03",
"Level04",
"Level05",
"Level06",
};
float[] mapHeights =
{
.999f, 1.499f, 1.999f, 2.499f, 2.999f, 3.499f
};
public int citySize = 100; //Only temporary
public int currentSize = 0;
public GameObject[] houses;
public Transform houseParent;
private void Start()
{
citySize = Random.Range(70, 120);
}
private void Update()
{
if (currentSize < citySize)
{
BuildHouse();
}
}
public void BuildHouse()
{
GameObject housePrefab = houses[Random.Range(0, houses.Length)];
int level = Random.Range(0, 6);
string mapLevel = mapLevels[level];
float height = mapHeights[level];
Vector3 randomPosition = new Vector3(Random.Range(-50f, 50f), height, Random.Range(-50f, 50f));
Quaternion randomRotation = Quaternion.identity;
var house = Instantiate(housePrefab, randomPosition, randomRotation);
house.GetComponent<House>().mapLevel = mapLevel;
house.GetComponent<House>().houseBuilder = GetComponent<HouseBuilder>();
house.transform.SetParent(houseParent);
currentSize++;
}
public void DestroyCity()
{
for (int i = 0; i <= houseParent.childCount - 1; i++)
{
Destroy(houseParent.GetChild(i).gameObject);
}
currentSize = 0;
}
}
This script checks if there is any wrong collision on a house and probably destroys it
public class House : MonoBehaviour
{
public bool badCollision = false;
public bool grounded = false;
public string mapLevel;
int timeStart = 3;
public HouseBuilder houseBuilder;
private void OnCollisionStay(Collision collision)
{
if (collision.collider.tag == "Props")
{
badCollision = true;
}
if (collision.collider.tag == "MapLevels" && collision.collider.name != mapLevel)
{
badCollision = true;
}
if (collision.collider.tag == "MapLevels" && collision.collider.name == mapLevel)
{
grounded = true;
}
}
private void Update()
{
timeStart--;
if (timeStart > 0) return;
if (badCollision || !grounded)
{
Destroy(gameObject);
houseBuilder.currentSize--;
}
}
}
What I observe is that I can move the cube around as I want, but nothing happens until I move it on the y so that it’s not colliding with two objects anymore but only with one. It seems that the issue has anything to do with that, but I don’t know why. Do you? I’d be really grateful… thx ![]()