首页 > 解决方案 > 材质编辑器中的着色器总是以固定值显示?(统一)

问题描述

我试图shader在运行时从对象中的附加值中获取一个值属性,但它在材质编辑器中永远不会改变。也许我误解了着色器的工作原理?

我阅读了有关GetFloat,GetColor等的信息,但还没有弄清楚它如何正确地获取shaderin的信息Update()。如果可能的话,这里的真正目标是(实时)捕获特定值shader并在 C# 脚本中执行某些操作。

C# 示例:

public Color colorInfo;

Awake()
{
    rend = GetComponent<Renderer>();// Get renderer
    rend.material.shader = Shader.Find("Unlit/shadowCreatures");//shader
}

Update()// I want the info in a realtime
{
    //get current float state of the shader
    colorInfo = rend.material.GetColor("_Color"); 
    //If I setup a white color in shader properties, the color in material editor is always white
}

着色器:

Shader "Unlit/shadowCreatures"
{
Properties {
    _Color ("Color", Color) = (1,1,1,1)
    [PerRendererData]_MainTex ("Sprite Texture", 2D) = "white" {}
    _Cutoff("Shadow alpha cutoff", Range(0,1)) = 0.5
}
SubShader {
    Tags 
    { 
        "Queue"="Geometry"
        "RenderType"="TransparentCutout"
        "PreviewType"="Plane"
        "CanUseSpriteAtlas"="True"
    }
    LOD 200

    Cull Off

    CGPROGRAM
    // Lambert lighting model, and enable shadows on all light types
    #pragma surface surf Lambert addshadow fullforwardshadows

    // Use shader model 3.0 target, to get nicer looking lighting
    #pragma target 3.0

    sampler2D _MainTex;
    fixed4 _Color;
    fixed _Cutoff;

    struct Input
    {
        float2 uv_MainTex;
    };

    void surf (Input IN, inout SurfaceOutput o) {
        fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        o.Alpha = c.a;
        clip(o.Alpha - _Cutoff);
        _Color = (0,0,0,0); //trying turn to black just for a test, and nothing happens
    }
    ENDCG
}
FallBack "Diffuse"
}

感谢您的时间

标签: c#unity3dshader

解决方案


我想我知道你想做什么

事情不是这样的,对不起

将您的评论和问题拼凑在一起,这就是我认为您正在尝试解决的问题:

void surf (Input IN, inout SurfaceOutput o) {
    _Color = (0,0,0,0); //trying turn to black just for a test, and nothing happens
}

这并不像你认为的那样。那条线设置了这个 _Color

#pragma target 3.0

sampler2D _MainTex;
fixed4 _Color;
fixed _Cutoff; //here

不是这个:

Properties {
    _Color ("Color", Color) = (1,1,1,1) //here
    [PerRendererData]_MainTex ("Sprite Texture", 2D) = "white" {}
    _Cutoff("Shadow alpha cutoff", Range(0,1)) = 0.5
}

第二个是检查器面板中显示的内容,它与 CGPROGRAM 块的链接实际上是单向的,因为frag surfgeom都被多次并行调用,并且依赖于接收相同的数据,因此将Properties值读入完成后将丢弃 CGPROGRAM 和 CGPROGRAM 的值。

我不认为有任何方法可以让着色器 CGPROGRAM 执行任何可以从 C# 读取的操作(因为代码每帧运行数百次,你怎么知道从哪一个读取?)

我知道您可以获取属性(包括更改一个实例或所有实例的属性),但不能获取基础 CGPROGRAM 数据。我什至能想到解决这个问题的唯一方法是渲染到纹理然后读取纹理数据,这会很慢(同样,你会进入“哪个像素具有你想要的值”?)


推荐阅读