Code generated mesh not visible
Hi,
I'm doing a 2d side scroller and wanted to generate a mesh for the ground. I followed some advices from the net but I can't make the mesh visible.
I tried to solve it looking at the forum, I found many posts about but none of them solve my problem. I simplified the script to the moment where there is nothing else to simplify and it's still not working.
The mesh is not visible both in game and scene view (I checked while running the game). But when I double click the mesh in mesh filter componeni it is shown correctly in the preview window.
I thought it can be an issue of the graphic drivers but after updating them (i use Nvidia Geforce GT 630M) the issue remains.
The scirpt is attached to an empty game object (with only transform component). Code is very simple:
public class PolygonTester : MonoBehaviour {
private Mesh terrainMesh;
private void Start()
{
Vector3[] vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(10, 0, 0), new Vector3(10, 10, 0), new Vector3(0, 10, 0) };
Vector2[] uv = new Vector2[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 1) };
int[] triangles = new int[] { 0, 1, 2 ,2,3,0};
terrainMesh = new Mesh();
terrainMesh.SetVertices(new List<Vector3>(vertices));
terrainMesh.SetUVs(0,new List<Vector2>(uv));
terrainMesh.SetTriangles(triangles,0,true);
terrainMesh.RecalculateBounds();
terrainMesh.RecalculateNormals();
gameObject.AddComponent<MeshRenderer>();
gameObject.AddComponent<MeshFilter>().mesh = terrainMesh;
MeshRenderer rnd = GetComponent<MeshRenderer>();
rnd.sortingLayerID = 0;
rnd.sortingOrder = 100;
}
}
Could someone point me what else can I check?
Thnx
Answer by norther · Jan 02, 2017 at 10:30 PM
I found a solution for this issue. I seems that the problem occurs only when I create an Empty object for the mesh. When I created a Cube object (3D Object->Cube) instead it is working. Maybe the emty object in a 2d game is derived from another class then 3d object and is not capable of rendering meshes.
The Cube has MeshRenderer and MeshFilter components so I needed to adjust the code to load them instead of creating them in order to replace the mesh and set sorting layer.
I had a similar issue and it was because I didn't add a mesh renderer to the empty object.