Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
1
Question by TheGamer106 · Apr 17, 2012 at 11:36 AM · randomgeneration

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

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
5
Best Answer

Answer by Graham-Dunnett · Apr 17, 2012 at 12:11 PM

 // 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];
     }
     
     Debug.Log(code);
 }

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.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TheGamer106 · Apr 17, 2012 at 12:29 PM 0
Share

Hm.. The Random.Range(0, characters); is giving me an error "BCE0023: No appropriate version of 'UnityEngine.Random.Range' for the argument list '(int, String)' was found" Any thoughts?

avatar image Lo0NuhtiK · Apr 17, 2012 at 12:33 PM 0
Share

characters.length

avatar image TheGamer106 · Apr 17, 2012 at 12:36 PM 0
Share

Whoo! It works :) Thanks for your help.

avatar image shaneparsons · Jun 08, 2016 at 06:29 PM 0
Share

It's not really an issue, but lowercase y and z are missing from the string.

avatar image
1

Answer by Davidovich · Apr 17, 2012 at 12:36 PM

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()!

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ModernAlchemist · Aug 26, 2015 at 12:56 PM 0
Share

Shouldn´t it be ... code += characters[Random.Range(0, characters.length-1)]; ... to avoid an index out of bounds exception because Random.Range includes the limits in the result.

avatar image Bunny83 ModernAlchemist · Sep 23, 2015 at 03:39 PM 0
Share

@$$anonymous$$odernAlchemist:
No Random.Range with int parameters is $$anonymous$$ includive and max exclusive. With float parameters $$anonymous$$ and max are theoretically both inclusive but that's such a rare case.

avatar image Gerold_Meisinger ModernAlchemist · Sep 24, 2015 at 05:54 AM 0
Share

Also see this code snippet which tests that very property.

avatar image
1

Answer by MrLucid72 · Aug 13, 2020 at 04:09 AM

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)];
         codeSB.Append(singleChar);
     }
 
     Debug.Log("GenerateRandomAlphaNumericStr: " + codeSB.ToString());
 
     return codeSB.ToString();
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Code to randomly generate a mesh? 0 Answers

how can i make randomly generated worlds with collectable resources 0 Answers

Infinite loop when I try to generate randomly a 2D dungeon.. 3 Answers

How can I make a Terraria Style game from sprites without using an enormous amount of gameobjects? 2 Answers

Random Island Generation 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges