Random Colors

From Shader Forge Wiki
Jump to: navigation, search

Say you have some kind of asset used quite often in your game, and you wish to have some color variation on it every here and there to break the repetitive nature of it. You might solve this by having a bunch of different materials, each with a different tint. While this is all good, it's a bit tedious, and certainly not as cool as what I'm about to show here.


What-If.jpg


Well, random is never random when it comes to computers, and in shaders it's even harder. You can however generate values which appear very much random to humans! For the case we are talking about, it would be quite cool if simply having a different position for an object would cause it to have another color. Let's do just that!


Random-color.png


Although not obvious, this tints our cube based on randomly colored pixels in the Texture2D node called TintTexture. We use the object position to generate our "random" value. We add all the axis together in order to have all the axis affect the color, then feed that to Sine to generate a value between -1 to 1. You'll then want to multiply this value with a very high value, to make sure it feels entirely random when using the value to sample the tint texture. We then append that value with itself to generate a Vector 2 for input to UV of the tint texture. Doing this, you might realize it will only travel diagonally in your tint texture, skipping values at 2 of the corners entirely, which is why it makes most sense if you use a 1px high texture which is just a line of colors you want to randomize between. For this example though I used a texture you can find in the old Standard Assets package that comes with Unity. You can see what the texture looks like when it's UV isn't generated from world coordinates in the disconnected node called Reference. It's just a bunch of pixels with colors (like textures in general o_O).

If you use this shader on an object and drag it around in the scene, it will flicker with the colors from the Tint Texture. It might be cool as an effect for a moving object, but what it's really meant to be used for is making the life of a level designer easier. So when a level designer places the same barrel or flag or whatever, here and there in a level, it'll look different every time thanks to the tint texture. Perhaps obvious, but it's recommended to use different Tint textures depending on the type of object, so the barrel might simply have shades of brown, while the flag could have more colorful... colors.

It's very much worth noting this is not the only way to do the effect, it's just one that I like since it gives you a lot of control with the Tint Texture.