直接上代码:
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;public class GLWireMesh : MonoBehaviour
{[Serializable]public class IntPair{public int a;public int b;public IntPair(int a, int b){this.a = a;this.b = b;}public bool Same(IntPair intPair){if (intPair.a == a && intPair.b == b) return true;if (intPair.a == b && intPair.b == a) return true;return false;}public override string ToString(){return "(" + a + "," + b + ")";}}[SerializeField]Material matWire;Mesh _mesh;Mesh mesh{get{if (!_mesh){MeshFilter filter = GetComponent<MeshFilter>();if (!filter) return null;_mesh = filter.mesh;}return _mesh;}}Vector3[] verts;IntPair[] intPairs;void Start(){if (!mesh) return;if (mesh){verts = mesh.vertices;int[] triangles = mesh.triangles;if (triangles != null && triangles.Length > 0){List<IntPair> intPairList = new List<IntPair>();for (int i = 0; i < triangles.Length; i += 3){intPairList.Add(new IntPair(triangles[i], triangles[i + 1]));intPairList.Add(new IntPair(triangles[i], triangles[i + 2]));intPairList.Add(new IntPair(triangles[i + 1], triangles[i + 2]));}List<IntPair> intPairWithoutRepetition = new List<IntPair>();intPairWithoutRepetition.Add(intPairList[0]);for (int i = 1; i < intPairList.Count - 1; i++){bool hasIP = false;foreach (IntPair ip in intPairWithoutRepetition){if (intPairList[i].Same(ip)){hasIP = true;break;}}if (!hasIP){intPairWithoutRepetition.Add(intPairList[i]);}}intPairs = intPairWithoutRepetition.ToArray();}}}void OnEnable(){if (!mesh) return;RenderPipelineManager.endCameraRendering += EndCameraRendering;}void OnDisable(){if (!mesh) return;RenderPipelineManager.endCameraRendering -= EndCameraRendering;}void EndCameraRendering(ScriptableRenderContext context, Camera camera){if (verts == null) return;if (verts.Length <= 0) return;if (intPairs == null) return;if (intPairs.Length <= 0) return;matWire.SetPass(0);GL.MultMatrix(transform.localToWorldMatrix);GL.Begin(GL.LINES);for (int i = 0; i < intPairs.Length; i++){GL.Vertex(verts[intPairs[i].a]);GL.Vertex(verts[intPairs[i].b]);}GL.End();}
}
Shader参考: