I had a hard time changing the texture of a game object in real-time where I tried out a movie fading between textures and using Lerp on the material. I wanted it to be dynamic and just be able to pass an argument to my script defining which texture to animate to. Many game objects had different shaders so it didn’t work just to Lerp the current material. So I create custom shaders for different objects that contained 2 textures “_MainTex” and “_Texture2″. I also added the blend option the the shader order to be able to control the blend of the texture from outside. Just adding the shader you can change the blend slider to see the result.
See example of one diffuse shader with normal map.
In my javascript I could then pass in which texture to change to and which one to change from.
I set the textures I want to change between. These are set in the inspector of athouring environment of Unity and passed to the script.
var secondTexture:Texture;
var thirdTexture:Texture;
The script starts out with setting the default texture of the chosen game object. The game object could have been passed to the script as well.
textureObject = gameObject.Find("myTextureObject");
textureObject.renderer.material.SetFloat( "_Blend", 1 ); // Setting the current texture to be 100% visible
}
The public function changeTexture can be accessed from outside to recieve arguments for new textures. newTexture is used to store the new texture as soon as it is time to animate.
yield WaitForSeconds(0.3);
if(myArg == 1) {
newTexture = firstTexture;
} else if (myArg == 2){
newTexture = secondTexture;
} else if (myArg == 3){
newTexture = thirdTexture;
}
textureObject.renderer.material.mainTexture = newTexture;
triggerChange = true;
}
In the update function the script always checks if it should change to a new texture. If changeTexture was called it starts blending to the new texture. At the end it sets the old texture to the new one and resets the blend:
if(triggerChange == true) {
changeCount = changeCount - 0.05;
textureObject.renderer.material.SetFloat( "_Blend", changeCount );
if(changeCount <= 0) {
triggerChange = false;
changeCount = 1.0;
textureObject.renderer.material.SetTexture ("_Texture2", newTexture);
textureObject.renderer.material.SetFloat( "_Blend", 1);
}
}
}
BlendTextures.js is the entire javascript file of the script above.
To implement this in Unity follow these steps:
1. Add your script to the scene. Select the textures and normalmap you defined as public variables in BlendTextures.js.
2. Create a material and choose your custom shader.
3. Add the material to your game object.
Read up on how to create your custom shaders in the Unity Documentation.















