Random code generation

Hi, I have a fairly simple question to ask here… Or, at least I hope it’s simple… What I want to do is have my .js script to generate a random authentication code and, for now, just print it to the console. So, something like this

“Random code: aAs12eIad091ueQp5Pq249”

would be printed. I think Random.Range() might do it, but I don’t know how to make it print characters alongside the numbers.

Many thanks, TG106

// Javascript example follows
private var characters : String = “0123456789abcdefghijklmnopqrstuvwxABCDEFGHIJKLMNOPQRSTUVWXYZ”;

function Start () {
	var code : String = "";
	for (var i : int = 0; i < 20; i++) {
		var a : int = Random.Range(0, characters.length);
		code = code + characters[a];

This code uses Random.Range to pick a random character from a String that contains all the characters you want to allow in your authentication code. Note that if you want to be secure, you might be better off using a library that provides this kind of security.

A common way of doing this is to specify the character set for your random code in an array, then pull random items out of that array to build the string. Like so:

var desiredCodeLength = 15;
var code = "";
characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray();
while(code.Length < desiredCodeLength) {
	code += characters[Random.Range(0, characters.length)];
Debug.Log("Random code: " + code);

You were on the right track with Random.Range()!

Based off @Davidovich , but with slightly more efficiency, readability, better typings (instead of var) and .Length typo fixed wrapped in a static func:

/// <summary>
/// 0-9 A-Z a-z (Length of roomName === 6; up from 4). 
/// https://answers.unity.com/questions/241219/random-code-generation.html
/// </summary>
/// <returns></returns>
public static string GenerateRandomAlphaNumericStr(int desiredLength)
    StringBuilder codeSB = new StringBuilder(""); // Requires @ top: using System.Text;
    char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray();
    char singleChar;

    while (codeSB.Length < desiredLength)
        singleChar = chars[UnityEngine.Random.Range(0, chars.Length)];

    Debug.Log("GenerateRandomAlphaNumericStr: " + codeSB.ToString());

    return codeSB.ToString();