How to generate random numbers in Unity with C# and shader code

I've recently set out on the task to learn everything about shaders in Unity. One of the problems I encountered was how to generate random numbers in a shader? The problem is that shaders don't have a built-in function to generate random numbers. Unity's built in function, at least if you are using C#, is called Random.Range(), and it will give you a random number. But there's no similar function if you are programming a shader and need random numbers, so you have to come up with another solution.

Introduction to random numbers

What are we doing here? We are going to generate random numbers with a so-called Random Number Generator (RNG). According to Wikipedia, an RNG is "a computational or physical device designed to generate a sequence of numbers or symbols that cannot be reasonably predicted better than by a random chance." This is actually more difficult than it first may sound. The reason is that it's impossible, as far as humanity knows, to generate random numbers in a computer with an algorithm. So the world of random number generation is divided into two groups:

  1. True random numbers generators (TRNG). These are really random numbers. Someone argued that you could generate these from cats walking on keyboards and detecting which keys are pressed. But you may actually be able to predict the "random" numbers if you know the size of the cat, so that's not going to work. What you will need is some physical phenomenon that is expected to be random.
    • The points in time at which a radioactive source decays are completely unpredictable.
    • Atmospheric noise, which is quite easy to pick up with a normal radio, is also considered random. Random.org is generating randomness from atmospheric noise.
    • What about the background noise in a cafĂ©? Maybe you can record that and see if it's random?
    • What happens if you combine all sources?
  2. Pseudo random number generators (PRNG). These are fake random numbers, so they are not entirely random because you are generating them with an algorithm. These numbers will work in many cases, but not in all. If you are visiting an online poker site, and you know the algorithm used to generate the "random" numbers, you can write a program that will predict the cards that are going to be dealt. So if you are running a poker site, you have to use a TRNG.

This tutorial is divided into the following sections:

Read more