URP基于GL的Unity物体网格线绘制方法参考

直接上代码:

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();
				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 intPairList = new List();
				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 intPairWithoutRepetition = new List();
				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参考:

URP基于GL的Unity物体网格线绘制方法参考_第1张图片

你可能感兴趣的:(Unity,Shader,unity)