A simple cross fade shader for Unity

The other day I was putting some polish to Deathfire‘s character generation and we wanted to fade character portraits from one to another when the player makes his selections. Unlike hard cuts, cross fades simply add a bit of elegance to the program that we did not want to miss.

I went through Unity’s documentation and very quickly came across its Material.Lerp function. Just what I needed, I thought, but after a quick implementation it turned out it didn’t do what I had had in mind. I had not read the function description properly, because what it does, is blend between the parameters of two materials and not the actual image the material creates. Since I am working with a texture atlas, this gave me a cool scrolling effect as my material lerped from one end of the atlas to the other but not the kind of cross fade I had had in mind.

It turns out that Unity doesn’t really have the functionality, so I dug a bit deeper and found Ellen’s approach to blending textures. A quick check of her sources showed me that it still did not do what I wanted, but it gave me a good basis to start from as I began writing my own implement of a simple cross fader.

It all starts with the shader itself, which takes two textures without a normal map and renders them on top of another. A variable tells the shader how transparent the top texture should be so we can adjust it on the fly and gradually blend from the first texture to the second. The key feature for my approach was that the shader uses UV coordinates for each of the textures to allow me to use the shader with a texture atlas.

Shader "CrossFade"
{
  Properties
  {
    _Blend ( "Blend", Range ( 0, 1 ) ) = 0.5
    _Color ( "Main Color", Color ) = ( 1, 1, 1, 1 )
    _MainTex ( "Texture 1", 2D ) = "white" {}
    _Texture2 ( "Texture 2", 2D ) = ""
  }

  SubShader
  {
    Tags { "RenderType"="Opaque" }
    LOD 300
    Pass
    {
      SetTexture[_MainTex]
      SetTexture[_Texture2]
      {
        ConstantColor ( 0, 0, 0, [_Blend] )
        Combine texture Lerp( constant ) previous
      }    
    }
  
    CGPROGRAM
    #pragma surface surf Lambert
    
    sampler2D _MainTex;
    sampler2D _Texture2;
    fixed4 _Color;
    float _Blend;
    
    struct Input
    {
      float2 uv_MainTex;
      float2 uv_Texture2;
    };
    
    void surf ( Input IN, inout SurfaceOutput o )
    {
      fixed4 t1  = tex2D( _MainTex, IN.uv_MainTex ) * _Color;
      fixed4 t2  = tex2D ( _Texture2, IN.uv_Texture2 ) * _Color;
      o.Albedo  = lerp( t1, t2, _Blend );
    }
    ENDCG
  }
  FallBack "Diffuse"
}

The second part of the implementation is the C# script that will drive the actual cross fade. It is pretty straight-forward and consists of an initialization function Start(), an Update() function that is called periodically and adjusts the blend factor for the second texture until the fade is complete. And then, of course, there is a function CrossFadeTo() that you call to set up the respective cross fade.

using UnityEngine;
using System.Collections;

public class CrossFade : MonoBehaviour
{
  private Texture    newTexture;
  private Vector2    newOffset;
  private Vector2    newTiling;
  
  public  float    BlendSpeed = 3.0f;
  
  private bool    trigger = false;
  private float    fader = 0f;
  
  void Start ()
  {
    renderer.material.SetFloat( "_Blend", 0f );
  }
  
  void Update ()
  {
    if ( true == trigger )
    {
      fader += Time.deltaTime * BlendSpeed;
      
      renderer.material.SetFloat( "_Blend", fader );
      
      if ( fader >= 1.0f )
      {
        trigger = false;
        fader = 0f;
        
        renderer.material.SetTexture ("_MainTex", newTexture );
        renderer.material.SetTextureOffset ( "_MainTex", newOffset );
        renderer.material.SetTextureScale ( "_MainTex", newTiling );
        renderer.material.SetFloat( "_Blend", 0f );
      }
    }
  }
  
  public void CrossFadeTo( Texture curTexture, Vector2 offset, Vector2 tiling )
  {
    newOffset = offset;
    newTiling = tiling;
    newTexture = curTexture;
    renderer.material.SetTexture( "_Texture2", curTexture );
    renderer.material.SetTextureOffset ( "_Texture2", newOffset );
    renderer.material.SetTextureScale ( "_Texture2", newTiling );
    trigger = true;
  }
}

The script also contains a public variable called BlendSpeed, which is used to determine how quickly the fade will occur. Smaller numbers will result in slower fades, while larger numbers create more rapid cross fades.

In order to use these scripts, all you have to do is add the shader and the script to your Unity project. Attach the C# script to the object you want to perform the cross fade and then from your application simply call CrossFadeTo() with proper texture parameters to make it happen. That is all there really is to it.


  CrossFade bt = gameObject.GetComponent();
  bt.CrossFadeTo( myTexture, myUVOffset, myScale );

I hope some of you may find this little script useful.

Facebooktwitterredditpinterestlinkedinmail

6 Replies to “A simple cross fade shader for Unity”

  1. Jens

    Hi Guido,

    may I ask what IDE you are using (Xamarin e.g.)? I assume you develop with a Mac.

    Greetings from Bielefeld/Germany,

    Jens

  2. Jens

    Thanks for the info. I am currently getting into touch with MonoTouch (Xamarin) for OS-independent mobile development with C#. Keep enjoy building Deathfire!

Leave a Reply

Your email address will not be published.