Search Unity

Remove repeated string from while using Random.Range

Discussion in 'Scripting' started by alexchandriyaa, Sep 10, 2018.

  1. alexchandriyaa

    alexchandriyaa

    Joined:
    Jan 18, 2017
    Posts:
    140
    am generating string using Random.Range i need to know how to avoid repeating string, the string should generated only once in a game this is my code
    Code (CSharp):
    1.  
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class GameController : MonoBehaviour {
    5.     public static string currentWord;
    6.     public Transform spellWord;
    7.    
    8.     public TextAsset textFile;
    9.     string[] letters;
    10.     public List<Transform> availablesetLetters = new List<Transform>();
    11.     // Use this for initialization
    12.     void Start ()
    13.     {
    14.        
    15.    
    16.     }
    17.     // Update is called once per frame
    18.     public void Update ()
    19.     {
    20.        
    21.         //space for storing typed words
    22.     }
    23.     public void Generate()
    24.     {
    25.         letters = (textFile.text.Split('\n'));
    26.         string dialog = letters[UnityEngine.Random.Range(0, letters.Length)];
    27.         //Debug.Log(dialog);
    28.         for (int i = 0; i <= 9; i++)
    29.         {
    30.             availablesetLetters[i].GetComponent<TextMesh>().text = dialog[i].ToString();
    31.          
    32.         }
    33.     }
    34.    
    35.     }
    36.        
    37.        
    38.  
    39.  
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,445
    "The string should only generate once in a game." This is the key phrase of your problem.

    You will need to keep a record of all the strings generated, and then avoid generating some string that was already generated in the past.

    Unless you're creating billions of strings, this should be an easy task.

    Pseudocode I haven't tested, fill it out:

    Code (csharp):
    1.  
    2. HashSet<string> wordsPreviouslyGenerated = new HashSet<string>();
    3.  
    4. string GenerateFreshWord()
    5. {
    6.     int tries = 0;
    7.     while (tries < 1000)
    8.     {
    9.          tries++;
    10.          string newWord = // come up with a string here
    11.          if ( ! wordsPreviouslyGenerated.Contains(newWord))
    12.          {
    13.             wordsPreviouslyGenerated.Add(newWord);
    14.             return newWord;
    15.          }
    16.     }
    17.     Debug.LogWarning("Took too long to come up with a new word, all the good ones have been taken.");
    18.     return "argleflarglebargle";
    19. }