Quantcast
Viewing latest article 3
Browse Latest Browse All 18

Modifying Sub-Meshes at Runtime & MeshRenderer

I've been working on creating meshes in code, and ran into a hitch.

When modifying the subMeshCount, and then reassigning the corresponding materials on the renderer, very strange things happen if I am working with an existing mesh object.

I'm calling mesh.Clear(), modifying the subMeshCount, and reassigning all verts, and triangles, etc. I am then updating the MeshRenderer materials array.

However, unless I destroy the MeshRenderer and then re-add it, the displayed mesh is not correct, that is, it isn't the same mesh I've modified (proven by querying the mesh in code). Is this expected behavior, or a bug? Has anyone successfully modified the subMeshCount (from 1 to 3 or more) of an existing mesh at runtime, and lived to tell the tale?

Up until this point, modifying meshes from code has worked pretty well, but when modifying the subMeshCount, the rendering explodes, short of my 'hack' described above.

--Here is the working code, without destroying and re-adding the MeshRenderer, odd things ensue:

private void ResetSubMeshLength(){

    myMesh.Clear();

    myMesh.subMeshCount = myMaterials.Length;
    AddRenderer(); //Without this function, hilarity ensues...

    meshRenderer.renderer.materials = myMaterials;

	InitializeTriangles();  //creates triangle holder, extends array
	BuildTriangles(); //init an ArrayList for each subMesh group of tris
	UpdateMesh();  //add verts, triangles, etc...
}

private void AddRenderer(){
	if(meshRenderer){
    	DestroyImmediate(meshRenderer);
	}    		
    gameObject.AddComponent(typeof(MeshRenderer));
    meshRenderer = (MeshRenderer)GetComponent(typeof(MeshRenderer));

}

and the update mesh function, just fyi....

public void UpdateMesh(){

	// Have all existing sprites re-apply their data
	foreach(UISprite sprite in UISprites) {
		sprite.AddToMesh(); //gets each quads data - updates arrays
	}

	myMesh.vertices = theVertices;
	myMesh.uv = theUVs;
	myMesh.colors = theColors;
	//better to find a way to use int[] directly, this is tedious and slow
	for(int i = 0; i< totalTriangles.Length; i++){
		int tricount = totalTriangles[i].triangles.Count;
		int[] tris = new int[tricount];
		for(int j=0; j<tricount; j++){
			tris[j] = (int)totalTriangles[i].triangles[j];
		}	
		myMesh.SetTriangles(tris,i);	
	}
	myMesh.RecalculateBounds();
}

Viewing latest article 3
Browse Latest Browse All 18

Trending Articles