using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridController : MonoBehaviour
{
private void Start()
{
ForAllChildren(transform, RebuildMesh);
}
private void RebuildMesh(Transform transform)
{
MeshFilter meshFilter = transform.GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.mesh != null)
{
int[] indices = MakeIndices(meshFilter.mesh.triangles);
meshFilter.mesh.SetIndices(indices, MeshTopology.Lines, 0);
}
}
private int[] MakeIndices(int[] triangles)
{
int[] indices = new int[2 * triangles.Length];
for (int i = 0; i < triangles.Length; i += 3)
{
for (int j = 0; j < 6; j++)
{
// 每个三角形转换为3条线段, 每个顶点使用2次, 对应的顶点序列是: 0, 1, 1, 2, 2, 0, 通式: (j + 1) % 6 / 2, j 的范围: 0 ~ 5
indices[2 * i + j] = triangles[i + (j + 1) % 6 / 2];
}
}
return indices;
}
private void ForAllChildren(Transform transform, Action<Transform> action)
{
action.Invoke(transform);
for (int i = 0; i < transform.childCount; i++)
{
ForAllChildren(transform.GetChild(i), action);
}
}
}