UnityShader自定义cginc文件

1.概述

        在使用UnityShader开发中,经常需要引入cginc文件,比如UnityCG.cginc。这些文件声明了很多内置的辅助函数和数据结构体,可避免大量重复编码工作。那么在实际开发中其实也需要把一些函数给封装起来,方便调用,那么就需要把这些函数写到自定义的cginc里面了。

2.创建cginc文件

        创建cginc文件其实很简单。首先找到Unity自带的cginc文件位置,在 Unity安装目录下的 Editor > Data > CGInclude 文件夹下,复制一个cginc文件,放到Unity工程里。然后将该文件名称修改为Mycginc,删除掉原来里面的内容,添加自己写的函数或者数据结构体。例如代码:

float4 sampleMvxTex(sampler2D texture2d, float2 UV)
{
    float4 clr;
    clr = tex2D(texture2d, UV);
    return clr;
}

3.引用cginc文件

        cginc文件创建完之后就需要去引用了。在Unity中通过Create>Shader>Unilt Shader创建一个Shader改名为MyShader。使用#include "Mycginc.cginc"引入自定义cginc文件,然后调用sampleMvxTex方法。代码如下:

Shader "Custom/MyShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"
             //引入自定义cginc文件
            #include "Mycginc.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                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);
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                //fixed4 col = tex2D(_MainTex, i.uv);      //注释掉原来的方法
                // apply fog
                UNITY_APPLY_FOG(i.fogCoord, col);
                //引用自定义cginc的方法
                return sampleMvxTex(_MainTex, i.uv);;
            }
            ENDCG
        }
    }
}

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YanisWu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值