更改已从资产包实例化的运行时创建物料的属性

时间:2018-10-03 10:13:58

标签: c# unity3d shader

我们正在从资产捆绑中加载资产。一切都包含在资产捆绑中。 我们的资产捆绑中有一个名称为 light_bulb_tex 的材料。我们已经编写了一个着色器,这是着色器代码,(此材料使用此着色器):

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'

Shader "Porject/FX/ColorDimmer" {
    Properties {
        _Color ("Color",Color)=(1.0, 1.0, 1.0, 1.0)
        _OffColor ("OffColor",Color)=(0.772, 0.772, 0.772)
        _Intensity("Intensity",Range (0, 1))=0
    }

    CGINCLUDE

        #include "UnityCG.cginc"

        sampler2D _MainTex;
        uniform fixed4 _Color;
        uniform fixed4 _OffColor;
        uniform fixed _Intensity;
        half4 _MainTex_ST;

        struct v2f {
            half4 pos : SV_POSITION;
            half2 uv : TEXCOORD0;
        };

        v2f vert(appdata_full v) {
            v2f o;

            o.pos = UnityObjectToClipPos (v.vertex);    
            o.uv.xy = TRANSFORM_TEX(v.texcoord, _MainTex);

            return o; 
        }

        fixed4 frag( v2f i ) : COLOR {  
            fixed4 texColor= tex2D (_MainTex, i.uv.xy) ;
            //fixed4 colorWithIntensity = 
            return lerp(_OffColor,_Color,_Intensity);
        }

    ENDCG

    SubShader {
    Tags{ "LightMode" = "ForwardBase" }

    Pass {

        CGPROGRAM

        #pragma vertex vert
        #pragma fragment frag
        #pragma fragmentoption ARB_precision_hint_fastest 

        ENDCG

        }

    } 
    FallBack Off
}

着色器也包含在资产捆绑中,并且已添加到游戏的“始终包含的着色器” 列表中。因此,我们将ColorDimmer着色器添加到了我们的项目中。

因此,当我们下载了资产捆绑包时,通过这段代码,我们将实例化游戏对象。素材会通过资产捆绑自动添加到实例化的游戏对象中。

...
/* objectRenderer.material is added to the _instancedGameObject 
from asset bundle. here we want to create
copy of this material. so newMaterial is
just copy of objectRenderer.material with 
it's specific shader (loading from app), in this case ColorDimmer is the shader which will be added to the newMaterial. */

var objectRenderer = _instancedGameObject.GetComponent<Renderer>();
var objectInAssetBundleMaterial = objectRenderer.material;
if (shaderName == "Proejct/FX/ColorDimmer")
{
    Material newMaterial = new Material(Shader.Find("Proejct/FX/ColorDimmer"));
    newMaterial.SetColor("_Color", objectInAssetBundleMaterial.GetColor("_Color"));
    newMaterial.name = System.Guid.NewGuid().ToString();
    objectRenderer.material = newMaterial;
}
...

我不知道为什么 objectInAssetBundleMaterial.GetColor(_Color)返回黑色。检查器中的所有内容看起来都不错,材质已正确加载了着色器。资产束中相应的mat文件也是在YAML中定义的,如下所示:

 ....
    m_Colors:
    - _Color: {r: 0.8088235, g: 0.18436417, b: 0.18436417, a: 1}
    - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
    - _OffColor: {r: 0.77205884, g: 0.77205884, b: 0.77205884, a: 1}

您会看到 _Color 不是黑色。

如何调用GetColor以获取_Color的值?

0 个答案:

没有答案