Unity如何在运行/构建模式显示网格线框?Gizmos.DrawMesh构建后不显示颜色
Unity运行模式及构建后显示网格线框的解决方案
为什么构建后看不到红色网格?
OnDrawGizmos是Unity编辑器专属的回调方法,构建后的独立应用不会执行该方法。Gizmos类的所有API仅在编辑器环境中生效,打包后的应用不会包含Gizmos的绘制逻辑,所以你设置的红色网格完全不会被渲染。
实现目标的两种可行方案
方案一:MeshRenderer + 线框材质(推荐)
这是最简便的方式,适合常规的网格线框显示需求:
- 创建线框材质:
- 在Project窗口右键选择
Create > Material - 将材质的Shader设为
Standard,Rendering Mode改为Wireframe - 把Albedo颜色调整为红色
- 在Project窗口右键选择
- 编写代码动态挂载组件:
如果你不想用Resources加载,也可以直接在Inspector面板给public Mesh targetMesh; private MeshFilter _meshFilter; private MeshRenderer _meshRenderer; void Start() { if (targetMesh == null) return; // 添加MeshFilter并绑定网格 _meshFilter = gameObject.AddComponent<MeshFilter>(); _meshFilter.mesh = targetMesh; // 添加MeshRenderer并绑定线框材质 _meshRenderer = gameObject.AddComponent<MeshRenderer>(); // 替换为你创建的线框材质的引用路径 _meshRenderer.material = Resources.Load<Material>("Materials/WireframeRed"); }_meshRenderer.material赋值。
方案二:GL类手动绘制(自定义性强)
适合需要自定义线框逻辑(比如只绘制特定边)的场景,GL类在运行时和构建后均有效:
public Mesh targetMesh; public Color lineColor = Color.red; private Material _lineMaterial; void Start() { // 创建GL绘制专用材质 _lineMaterial = new Material(Shader.Find("Hidden/Internal-Colored")); _lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); _lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); _lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); _lineMaterial.SetInt("_ZWrite", 0); } void OnRenderObject() { if (targetMesh == null || _lineMaterial == null) return; // 激活材质并设置绘制参数 _lineMaterial.SetPass(0); GL.PushMatrix(); GL.MultMatrix(transform.localToWorldMatrix); GL.Color(lineColor); // 遍历三角面绘制所有边 GL.Begin(GL.LINES); int[] triangles = targetMesh.triangles; Vector3[] vertices = targetMesh.vertices; for (int i = 0; i < triangles.Length; i += 3) { // 绘制三角形三条边 GL.Vertex(vertices[triangles[i]]); GL.Vertex(vertices[triangles[i + 1]]); GL.Vertex(vertices[triangles[i + 1]]); GL.Vertex(vertices[triangles[i + 2]]); GL.Vertex(vertices[triangles[i + 2]]); GL.Vertex(vertices[triangles[i]]); } GL.End(); GL.PopMatrix(); } void OnDestroy() { // 销毁材质避免内存泄漏 Destroy(_lineMaterial); }
内容的提问来源于stack exchange,提问作者N3.nguyễn Ngọc sơn
相关产品推荐
相关产品推荐

