今天看了下如何创建长方形和三角形,以前只是知道能够使用同一个Material的情况下就使用同一个,能减少Draw Calls ,今天自己也测试了一下,加深都理解。
我目前理解是为了降低Draw Calls 应当尽然重用 Materail,这中情况下,不管你创建多少个三角形,使用相同的Materail,那么Draw Calls只会+1,但是这种重用很有局限性,如果你改变Materail都颜色,那么所有都三角形都会改变颜色。从这点就应该大致知道为什么Draw Calls只会+1。
进而我尝试了创建多个三角形,每个三角形都实例化新都Materail,这种情况下,测试结果是在可视范围内,有多少个三角形,就会有多少Draw Calls 。这样就能清楚都知道Materail是增加Draw Calls都主要因素,所以以后得注意这一点。
下面贴出代码,创建三角形,长方形都代码以后应该能用到。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using UnityEngine; using System.Collections; public class MeshTest : MonoBehaviour { public Material material; // Use this for initialization void Start () { int i = 0; GameObject go = GetSquare(50, 50, material); go.transform.position = new Vector3(0, 0, 55 * i++); //go = GetSquare(50, 50, Color.black, material); //go.transform.position = new Vector3(0, 0, 55 * i++); GetTriangle(50, material); } /// <summary> /// 获取一个正方形 /// </summary> /// <returns></returns> public GameObject GetSquare(int width, int height, Material material) { GameObject go = new GameObject("Square"); MeshFilter filter = go.AddComponent<MeshFilter>(); Mesh mesh = new Mesh(); filter.sharedMesh = mesh; mesh.vertices = new Vector3[6] { new Vector3(0, 0, 0), new Vector3(0, 0, height), new Vector3(width, 0, 0), new Vector3(width, 0, height), new Vector3(width, 0, 0), new Vector3(0, 0, height) }; //mesh.colors = new Color[6] { color, color, color, color, color, color }; //设置每个顶点颜色 //mesh.uv = new Vector2[6] { new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 1), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 0) }; mesh.triangles = new int[6] { 0, 1, 2, 3, 4, 5 }; mesh.RecalculateNormals(); mesh.RecalculateBounds(); MeshRenderer render = go.AddComponent<MeshRenderer>(); //Material mate = new Material(Shader.Find("Diffuse")); //mate.SetColor("_Color", color); //material.SetTexture("_MainTex", texture); render.sharedMaterial = material; return go; } /// <summary> /// 获取一个三角形 /// </summary> public GameObject GetTriangle(int size, Material material) { GameObject go = new GameObject("Triangle"); MeshFilter filter = go.AddComponent<MeshFilter>(); Mesh mesh = new Mesh(); filter.sharedMesh = mesh; mesh.vertices = new Vector3[3] { new Vector3(0, 0, 0), new Vector3(0, 0, size), new Vector3(size, 0, 0)}; //mesh.colors = new Color[3] { color, color, color }; //设置每个顶点颜色 //mesh.uv = new Vector2[3] { new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 1) }; mesh.triangles = new int[3] { 0, 1, 2 }; mesh.RecalculateNormals(); mesh.RecalculateBounds(); MeshRenderer render = go.AddComponent<MeshRenderer>(); //Material material = new Material(Shader.Find("Diffuse")); //material.SetColor("_Color", color); //material.SetTexture("_MainTex", texture); render.sharedMaterial = material; return go; } } |