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

Unity Shader编译报错:标识符‘_FillAmount’未声明如何解决?

解决Unity Shader编译错误:未声明标识符‘_FillAmount’

问题根源:你仅在Shader的Properties块中声明了_FillAmount,但没有在CGPROGRAM代码块内声明对应的变量。Unity Shader中,Properties里的变量仅用于在编辑器面板显示,CG代码要访问该变量,必须在CG块里重新声明匹配类型的变量。

修正后的完整代码:

// draws circle pattern
Shader "UnityLibrary/2D/Patterns/Circles"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _CircleSize("Size", Range(0,1)) = 0.5
        _Circles("Amount", Range(1,64)) = 8
        _FillAmount("Fill", Range(0, 100)) = 3 // 调整Range为0-100,匹配你"值为0显示环形"的需求
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Standard fullforwardshadows vertex:vert
        #pragma target 3.0

        struct Input
        {
            float2 texcoord : TEXCOORD0;
        };

        sampler2D _MainTex;
        float _Circles;
        float _CircleSize;
        float _FillAmount; // 关键:添加此行声明,CG代码才能访问该变量

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        UNITY_INSTANCING_BUFFER_START(Props)
        UNITY_INSTANCING_BUFFER_END(Props)

        float2 tile(float2 _st, float _zoom)
        {
            _st *= _zoom;
            return frac(_st);
        }

        float Circle(float2 _st, float _radius)
        {
            float2 dist = _st - float2(0.5, 0.5);
            return 1. - smoothstep(_radius - (_radius * 0.01), _radius + (_radius * 0.01), dot(dist, dist) * 4.0);
        }

        void vert(inout appdata_full v, out Input o) 
        {
            UNITY_INITIALIZE_OUTPUT(Input, o);
            o.texcoord = v.texcoord;
        }

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            float2 st = IN.texcoord.xy;
            float radius = _CircleSize;

            float fillThreshold = radius * (_FillAmount / 100.0);
            float c = Circle(tile(st, round(_Circles)), radius);

            if (c >= fillThreshold) {
                o.Albedo = _Color;
            } else {
                o.Albedo = float3(0, 0, 0);
            }

            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = 1.0;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

额外说明:我将_FillAmount的Range从1,100调整为0,100,这样能精准实现你“值为0时显示环形”的需求,若不需要可改回原范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:05:17