Why does the usual C # Random not work in a Unity script?
I try this code to change the color channel at the touch of a button:

 void Update () { Random rnd = new Random(); if (Input.GetKeyUp (KeyCode.Space)) { byte value = rnd.Next(); } Color32 color32 = new Color32(4, 128, 192, value); obj.GetComponent <Renderer> ().material.color = color32; } 

Also, I do not understand how to set the interval in which generation will occur.

    1 answer 1

    For System.Random :

    The Next() method returns an int and you need an explicit cast to the byte type:

     byte value = (byte)rnd.Next(); 

    Or, in case of reluctance to use casting, the variant with the NextBytes method:

     var buffer = new byte[1]; rnd.NextBytes(buffer); byte value = buffer[0]; 

    The interval can be specified by overloading the Next method, which accepts two int numbers: minValue (inclusive) and maxValue (not inclusive).


    An option that should work for UnityEngine.Random :

     byte value = (byte)Random.Range(0, 256); 
    • to generate at first in int, and then to convert in byte? I understood correctly? - Jonathan
    • @Jonathan yes. The uniform distribution of the result should be maintained. - Regent
    • Writes such an error, on the first line: Error CS1023: Assembly-CSharp - Jonathan
    • And on NextByte: Error CS1061: Type UnityEngine.Random' does not contain a definition for NextBytes' and no extension method. Are you missing an assembly reference? (CS1061) (Assembly-CSharp) - Jonathan
    • one
      @Jonathan of course there is no such method. Considering that you wrote in the question that you are using the usual C # random Random ( System.Random ), but in fact, judging by the error text, you are using UnityEngine.Random . It is not good to mislead others. I UnityEngine.Random add to the end of the answer an option that may work for UnityEngine.Random . - Regent