What you will learn
In this tutorial you will learn how to make a shader with the Shader Graph so you can modify the color of part of a texture like this:
I used this methods to control the colors of the plane and of the bombs' fin in my recent game The Prabbits: Happy Dogfights! Here you see myself playing around with the newly colored bomb :)
Color Mask with Unity Shader Graph
When your object is made of multiple materials, it is easy to change the colour of its parts. However, most of the time, we try to keep the number of materials on screen low for performance reason. In that case the color information is within a texture and if you want to offer several colors of a same object, you might be tempted to make several textures altogether.
If you plan to support few colors, it is totally fine, but what if you want the player to be able to pick any color?
As the colour information of my bomb (or plane) is contained in a texture, we need to solve the problem with a custom shader, and it is actually easier than what I thought it would be to implement, thanks to Unity Graph Shader.
- In your 2D software make sure that the texture is in black and white where you want the color to be applied
- In your 2D software, create a new image (or layer) with a black background and paint in white where the color should be applied:
In Unity’s Project panel, right click in one of your asset folders and select
Create > Shader > PBR Graph, then double-click on the newly created asset. That should open up the Graph Shader.
Cliking on the + button, create the following exposed variables:
- Create a Sample Texture 2D node and attach it to the ColorTexture (i.e. hitting “spacebar”, start writing “Sample Text…” and select the node).
Create a Sample Texture 2D node and attach it to the ColorMask,
Create a Multiply node and attach the DecorationColor node and Sample Texture 2D to it,
- Combine the two branches with a Add node and connect the result to the Albedo channel of the PBR Master node:
And you are done!
- [Optional] You can also add a Smoothness and Roughness texture to the PBR Master node as I did below (note that I stored the Smoothness information in the alpha channel of my texture):
So, that’s it! You should be able to control the color of your object using the DecorationColor variable!
In a script, assuming that your color is stored in
m_PlayerColor, you will need to do:
I hope this helps you in your game development, don’t hesitate to share other methods in the comment below 🙂
See you around!