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

Unity技术问题:如何将PNG设为GL四边形的Texture2D?

问题分析与解决方案

核心问题

你用Standard Shader渲染GL直接绘制的四边形是错误选择——Standard是PBR材质,依赖光照、法线等额外顶点数据,但GL.Begin绘制时仅传递了位置和纹理坐标,缺少这些必要数据,所以只会显示黑色。另外你的纹理坐标也存在错误:GL.TexCoord2需要传入0到1之间的UV值,而非屏幕像素坐标。

解决步骤

1. 替换为适配的Shader

直接使用Unity内置的Unlit/Texture Shader,它是无光照的纯纹理渲染Shader,完全适配GL直接绘制的场景:

Shader shader2 = Shader.Find("Unlit/Texture");

如果需要支持透明通道,可改用Unlit/Transparent Shader,确保透明区域正常显示。

2. 修复纹理坐标

将基于屏幕像素的坐标修改为0-1范围的UV值:

GL.Begin(GL.QUADS);
// 左下
GL.TexCoord2(0, 0); 
GL.Vertex3(x, y, z);
// 右下
GL.TexCoord2(1, 0); 
GL.Vertex3(x + w, y, z);
// 右上
GL.TexCoord2(1, 1); 
GL.Vertex3(x + w, y + h, z);
// 左上
GL.TexCoord2(0, 1); 
GL.Vertex3(x, y + h, z);
GL.End();

3. (可选)自定义极简Shader

若内置Unlit Shader不符合需求,可自己编写一个最基础的纹理Shader:

Shader "Custom/BasicTexture"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "Queue"="Transparent" "RenderType"="Transparent" }
        LOD 100
        Blend SrcAlpha OneMinusSrcAlpha
        Cull Off
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

将该Shader保存为BasicTexture.shader,之后在代码中通过Shader.Find("Custom/BasicTexture")调用即可。

额外注意点

  • 加载纹理后,建议设置letter.wrapMode = TextureWrapMode.Clamp;避免纹理边缘出现重复问题
  • 可显式设置letter.alphaIsTransparency = true;,确保PNG的透明通道被正确识别

内容的提问来源于stack exchange,提问作者aarelovich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:50:23