Random Number's

In this tutorial we will learn about random number's.
There is no built-in function in Unity's Shader programming to generate a random number.


[IMPORTANT]
If you are visiting this website for the very first time, please have a look at the first tutorial, it would help you to understand this tutorial better. Click Here!

Bootstrap Themes

Project Setup

First add a plane then rotate it's face toward camera, or set the plane rotation to (90, 180, 0).
Add a unlit shader and apply it to a material, and apply that material to the plane.

open the Unlit Shader in Visual Studio.

Bootstrap Themes



With this rotation of plane, the origin of i.uv is bottom left corner.

Bootstrap Themes

In C# you can generate a random number using Random.Range(min,max) function, and this function uses some algorithm to generate a random number.

In unity shader programming we define our own algorithm's to generate random numbers.
Copy this function on left side and paste it above the fragment function in your shader code. as highlighted with green cell in right image.

This function requires an input of float2 and could return any value between 0.0 to 1.0
e.g 0.0 .. 0.25 .. 0.48 .. 0.69 .. 0.81 .. 1.0

float   RandomNumber ( float2   p )
{
p = frac( p * float2(234.34, 435.345) );
p += dot( p, p + 34.23 );
return frac(p.x * p.y);
}

Bootstrap Themes

Here is our first example.
At each pixel the value of i.uv.x & i.uv.y is different, if we pass it to the function RandomNumber(float2 p) it will return a number whithin the range (0.0 . 0.25 . 0.50 . 0.75 . 1.0).
& multiplying that number with the color will give use the following result.

At some pixel the color is white, at some the color is grey and at some pixel the color is black.

Bootstrap Themes
Bootstrap Themes

Add this line i.uv.x += _Time.y; (mentioned with yellow cell)
It will create an old TV like effect.

In the previous example the i.uv values were same at each frame, at each frame the values of i.uv reset to 0.0 .... 1.0 for both i.uv.x & i.uv.y & results in static image.
Because the function RandomNumber() generates the same result each time for same input, it's not dynamic.

In our current example the values of i.uv are not same at each frame. we are changing it each frame, so the function RandomNumber() will return dynamic values.

Bootstrap Themes