Topic: replace building mesh with a new one

Hi,

I am working on the function to  replace the building meshes with a kind of 'debris' meshes (created in Blender).
I made function to detect small buildings:

//in Start     
   buildingsControl.OnShowBuilding = OnShowBuilding;


 private bool OnShowBuilding(OnlineMapsBuildingBase onlineMapsBuildingBase)
    {
        var gMesh = debris1.GetComponent<MeshFilter>();
        var mesh = onlineMapsBuildingBase.GetComponent<MeshFilter>();

//detect building volume
        var size = VolumeOfMesh(mesh.mesh);
        if (size < 200000)
        {
//replace (bad way)
            mesh.mesh = gMesh.sharedMesh;
        }
        return true;
    }

I get an expected result.  But the new mesh is not of the previous building size and scale (apparently it is of its initial prefab size).

Could you please sugest a better way or idea to do this?

Re: replace building mesh with a new one

Hello.

You can get the size of the original building from the collider (GetComponent<Collider>().bounds), and calculate the scale.
But there is a small problem - when you change the zoom, you will lose your scale. So it is better to do in this way:

//in Start
buildingsControl.OnBuildingCreated += OnBuildingCreated;

private void OnBuildingCreated (OnlineMapsBuildingBase building)
{
        var gMesh = debris1.GetComponent<MeshFilter>();
        var mesh = building.GetComponent<MeshFilter>();

//detect building volume
        var size = VolumeOfMesh(mesh.mesh);
        if (size < 200000)
        {
            Collider cl = building.GetComponent<Collider>();
            Vector3 scale = CalculateScale(cl.bounds);
            OnlineMapsUtils.DestroyImmediate(building.GetComponent<MeshRenderer>());
            OnlineMapsUtils.DestroyImmediate(mesh);
            OnlineMapsUtils.DestroyImmediate(cl);
            GameObject newBuilding = Instantiate(debris1);
            newBuilding.transform.parent = building.transform;
            newBuilding.transform.localPosition = Vector3.zero;
            newBuilding.transform.localRotation = Quaternion.Euler(Vector3.zero);
            newBuilding.transform.localScale = scale;
        }
        return true;
}

P.S. This code is a theoretical and I haven't tested it.

Kind Regards,
Infinity Code Team.

Boost your productivity a lot and immediately using Ultimate Editor Enhancer. Trial and non-commerce versions available.