Home > Mobile >  Random name generator without duplicates in unity
Random name generator without duplicates in unity

Time:01-31

I'm trying to create a list which prints out a random name I've attached to a gameobject in unity. How would I go about stopping duplicates?

using TMPro;

public class Names : MonoBehaviour
{
    public List<string> names = new List<string>();
    public TMP_Text text;

    private void Start()
    {
        string wordToDisplay = RandomWord();

        text.text = wordToDisplay;
    }

    private string RandomWord()
    {
        {
            string randomName = names[Random.Range(0, names.Count)];
                       
            return randomName;
        }

    }
}

CodePudding user response:

Use something like this:

private Stack<string> _randomNames = null;
private string RandomWord()
{
    if (_randomNames == null || _randomNames.Count == 0)
    {
        _randomNames = new Stack<string>(names.OrderBy(n => Random.Range(0, int.MaxValue)));
    }
    return _randomNames.Pop();
}

It's effectively ordering the list randomly and then picking a value one at a time.

CodePudding user response:

As Uriil mentioned in the comment you could remove the new name from the list when you call RandomWord to guarantee uniqueness. Here is an example on how to achieve this:

    private string RandomWord()
    {
        {
            int index = Random.Range(0, names.Count);
            
            string randomName = names[index];
            names.RemoveAt(index);
            
            return randomName;
        }

    }
  •  Tags:  
  • Related