Unlit Shader下的Texture切换

Unity Shader 实现贴图过渡
本文介绍如何使用Unity Shader实现贴图之间的平滑过渡效果。通过定义MixValue参数,控制两个贴图间的渐变过程,并提供了一个Unity脚本实例,演示如何在运行时动态改变MixValue以达到平滑切换贴图的目的。

今天要实现一个贴图切换过渡的一个效果,Unlit的性能比较好,所以参考了网上一些Texture的shader之后,写了一下。

具体内容:MixValue 来完成渐变效果, MixValue = 1时为下面的Texture, MixValue = 0时为上面的Texutrue
Shader
下面是shader的代码:主要是frag 部分,通过mixvalue去进行两个贴图的颜色混合

Shader "Unlit/SwapTexture"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    _SubText("Texture", 2D) = "white"{}
    _MixValue("MixValue (Range)",Range(0,1)) = 0.5
  }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

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

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
      sampler2D _SubText;
      float _MixValue;
            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 main = tex2D(_MainTex, i.uv);
        fixed4 sub = tex2D(_SubText, i.uv);
                // apply fog
        main = main * (1 - _MixValue);
        sub = sub * _MixValue;
        fixed4 col = main + sub;
                UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

一个配套使用的脚本:挂在换贴图的物体上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class TextureSwapComp : MonoBehaviour {
  Renderer target;
  Shader shader;
  bool is_swaping;
  public int texture_index;
  // Use this for initialization
  private void Awake()
  {
    shader = Shader.Find("Unlit/SwapTexture");
    target = this.GetComponent<Renderer>();
    is_swaping = false;
  }

  private void Start()
  {
    ThemeManager.AddTextureSwap(this);
  }

  public void SwapTexture(Texture to, float time, Action action)
  {
    if (is_swaping) StopAllCoroutines();
    StartCoroutine(__Swap(to, time, action));
  }


  IEnumerator __Swap(Texture to, float time, Action action)
  {
    is_swaping = true;
    float timer = 0;
    float mix_value = 0;
    Material swaping_mat =  new Material(shader);
    Material currect_mat = target.material;

    swaping_mat.SetTexture("_MainTex", currect_mat.mainTexture);
    swaping_mat.SetTexture("_SubTex", to);
    swaping_mat.SetFloat("_MixValue", 0);
    target.material = swaping_mat;

    while (time >= timer)
    {
      timer += Time.deltaTime;
      mix_value = Mathf.Lerp(mix_value, 1, timer / time);
      swaping_mat.SetFloat("_MixValue", mix_value);
      yield return null;
    }

    currect_mat.SetTexture("_MainTex", to);
    target.material = currect_mat;

    currect_mat = null;
    swaping_mat = null;
    is_swaping = false;
    if (action != null) action();
  }

  private void OnDestroy()
  {
    StopAllCoroutines();
    ThemeManager.RemoveTextureSwap(this);
  }

  private void OnDisable()
  {
    StopAllCoroutines();
    ThemeManager.RemoveTextureSwap(this);
  }
}
### 使用着色器实现数字切换效果 为了实施数字切换效果,可以利用Unity中的自定义Shader功能。通过创建特定的Shader代码,在材质中应用该Shader并控制其参数变化来达到动态显示不同数字的目的。 #### 创建基本结构 首先按照标准流程建立一个新的Unlit类型的Shader文件: ```csharp Shader "Custom/DigitSwitcher" { Properties { _MainTex ("Texture", 2D) = "white" {} _DigitIndex("Current Digit Index", Range(0,9))=0 _Cols("Columns Count In Texture Atlas", Float)=10 _Rows("Rows Count In Texture Atlas", Float)=1 } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag struct appdata_t { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 pos : SV_POSITION; }; sampler2D _MainTex; float _DigitIndex; float _Cols; float _Rows; v2f vert (appdata_t v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.uv = v.uv; // Adjust UV coordinates based on the current digit index. int col = floor(_DigitIndex % _Cols); int row = floor(_DigitIndex / _Cols); o.uv.x *= (_Cols * 1.0/_Cols); o.uv.y *= (_Rows * 1.0/_Rows); o.uv += float2(col*(1.0/_Cols),row*(1.0/_Rows)); return o; } fixed4 frag (v2f i) : SV_Target { fixed4 col = tex2D(_MainTex, i.uv); clip(col.a - 0.1); // Discard transparent pixels to avoid artifacts return col; } ENDCG } } } ``` 这段代码实现了基于纹理图集(Sprite Sheet)的选择性采样机制[^1]。`_DigitIndex`用于指定当前应该展示哪个数字;而`_Cols`和`_Rows`则描述了整个纹理图集中有多少列和行。这样就可以在一个大图片里存储多个不同的数字图像,并且能够方便地在它们之间进行转换。 当调整这些属性时,比如改变_DigitIndex值,就会触发重新计算UV坐标从而显示出对应位置上的新图案。这使得可以在运行期间轻松更新所呈现出来的具体数值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值