简体   繁体   中英

How to skip values in Random.Range? In Unity/C#?

facing issue with randomising the randomLetter for non latin script. in my script, in the unicode characters table, 4 unicode values are non existent. need to skip those characters while Random.Range() is running. what is the workaround? declare an array? or declare a list? or something else? please help. Working code for Latin script:

{
private void OnEnable()
    {
        var i = UnityEngine.Random.Range(0, 26);
_randomLetter = (char) ('a' + i);

        GetComponent<TMP_Text>().text = _randomLetter.ToString();
    }

Bengali script code:

private void OnEnable()
    {
        var i = UnityEngine.Random.Range(0, 16);  //12 vowels in bengali but here 16 as range including non-existent values

        _randomLetter = (char) ('অ' + i);

        GetComponent<TMP_Text>().text = _randomLetter.ToString();

    }

easiest way is to build a list of all the allowed characters, and generate a random index into this list. Note that a string can be used like a list of characters.

const string allowedCharacters = "abe";
var randomIndex = UnityEngine.Random.Range(0,allowedCharacters.Length);
var randomCharacter = allowedCharacters[randomIndex];

Another easy way is to use rejection sampling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM