1
我從未使用子網格,但我幾乎讓它們工作。第二次嘗試設置meshRenderer材質的mainTexture時,出現'數組索引超出範圍'錯誤。我將subMeshCount設置爲2,並試圖在索引0和索引1處應用2個材質。我無法理解索引1如何超出範圍。是否有一些代碼可以告訴渲染器需要多少材料?感謝您的時間。Unity MeshRenderer.materials數組索引超出範圍
編輯:錯誤地解釋錯誤日誌。
void Update() {
List<Vector3> vertices = new List<Vector3>();
List<int> dirtTriangles = new List<int>();
List<int> grassTriangles = new List<int>();
List<Vector2> uvList = new List<Vector2>();
mesh.Clear();
//draw faces
addFace(mesh,uvList,vertices,dirtTriangles,DIR.front);
addFace (mesh,uvList,vertices,dirtTriangles,DIR.back);
addFace (mesh,uvList,vertices,dirtTriangles,DIR.left);
addFace (mesh,uvList,vertices,dirtTriangles,DIR.right);
addFace (mesh,uvList,vertices,grassTriangles,DIR.top);
addFace (mesh,uvList,vertices,dirtTriangles,DIR.bottom);
mesh.vertices = vertices.ToArray();
//mesh.triangles = triangles.ToArray();
mesh.subMeshCount = 2;
mesh.SetTriangles (dirtTriangles.ToArray(),0);
mesh.SetTriangles (grassTriangles.ToArray(),1);
mesh.RecalculateNormals();
mesh.uv = uvList.ToArray();
//set materials
meshRenderer.materials[0].mainTexture = Resources.Load("block_speckled") as Texture;
meshRenderer.materials[1].mainTexture = Resources.Load("block_grass") as Texture; //error
var shader = Shader.Find ("Particles/Alpha Blended");
meshRenderer.materials[0].shader = shader; //not sure if this is correct either
meshRenderer.materials[1].shader = shader;
}
不是基本相同的代碼,只是輕微的重構?關鍵區別是什麼? – Orange
關鍵的區別是你必須在訪問數組之前向數組添加材質。 meshRenderer.materials [0] .mainTexture = ... 正在工作,因爲您默認有一個元素數組。 –