- Home /
Question by
jni97 · Apr 03, 2016 at 09:27 AM ·
meshcombinemeshescombinechildrencombined meshcombineinstance
Mesh.CombineMesh() results in different heights between objects
Hi, I'm trying to create a Minecraft like Terrain. So each Chunk contains 16 * 16 blocks which should be combined into one mesh. To reach this, I wanted to use Mesh.CombineMesh(); The problem is, that the height between the Chunks is different after I created the Chunk mesh.
I won't have this problem if I don't combine the mesh. Is there a way to remove the height difference between the meshes?
This is my code, it might help! Thankful for any help!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Chunk : MonoBehaviour {
public void generateChunk(int chunkWidth, int chunkHeight, int chunkLength, float heightModifier, float perlinSize){
List<MeshFilter> meshfilters = new List<MeshFilter>();
for(int x = 0;x < chunkWidth;x++){
for(int z = 0;z < chunkLength;z++){
float h = Mathf.PerlinNoise((gameObject.transform.position.x * perlinSize) + (float)(x * perlinSize), (gameObject.transform.position.z * perlinSize) + (float)(z * perlinSize));
h *= heightModifier;
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
block.transform.SetParent(gameObject.transform);
block.transform.localPosition = new Vector3(Mathf.RoundToInt(x), Mathf.RoundToInt(h), Mathf.RoundToInt(z));
meshfilters.Add(block.GetComponent<MeshFilter>());
}
}
CombineInstance[] instance = new CombineInstance[meshfilters.Count];
for(int i = 0;i < meshfilters.Count;i++){
instance[i].mesh = meshfilters[i].sharedMesh;
instance[i].transform = meshfilters[i].gameObject.transform.localToWorldMatrix;
meshfilters[i].gameObject.SetActive(false);
}
gameObject.AddComponent<MeshFilter>().mesh = new Mesh();
gameObject.GetComponent<MeshFilter>().mesh.CombineMeshes(instance);
gameObject.GetComponent<MeshFilter>().mesh.Optimize();
gameObject.GetComponent<MeshFilter>().mesh.RecalculateBounds();
gameObject.AddComponent<MeshRenderer>().material = meshfilters[0].gameObject.GetComponent<Renderer>().material;
}
}
problem.png
(97.9 kB)
Comment
Best Answer
Answer by GoodyTong · Apr 03, 2016 at 09:52 AM
The GameObject that chunk script attached to, is it position at origin (0,0,0). If not can you try to move it to origin and try again.