You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity如何在运行/构建模式显示网格线框?Gizmos.DrawMesh构建后不显示颜色

Unity运行模式及构建后显示网格线框的解决方案

为什么构建后看不到红色网格?

  • OnDrawGizmos 是Unity编辑器专属的回调方法,构建后的独立应用不会执行该方法。
  • Gizmos 类的所有API仅在编辑器环境中生效,打包后的应用不会包含Gizmos的绘制逻辑,所以你设置的红色网格完全不会被渲染。

实现目标的两种可行方案

方案一:MeshRenderer + 线框材质(推荐)

这是最简便的方式,适合常规的网格线框显示需求:

  1. 创建线框材质:
    • 在Project窗口右键选择 Create > Material
    • 将材质的Shader设为 Standard,Rendering Mode改为 Wireframe
    • 把Albedo颜色调整为红色
  2. 编写代码动态挂载组件:
    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");
    }
    
    如果你不想用Resources加载,也可以直接在Inspector面板给_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:48:20