Search Unity

Pull random word from list

Discussion in 'Scripting' started by DrewClegg, Jan 29, 2020.

  1. DrewClegg

    DrewClegg

    Joined:
    Dec 22, 2019
    Posts:
    1
    Hey! I am trying out an idea where I have, say 3 separate lists of words, and would like to pull one Random word from each list to display.

    how would y’all go about scripting that? My ideas have lead to dead ends or non ideal results.

    I would like to be able to access and change the list(s) as needed. Do I just write it all as a string and pull from each string?
     
  2. Deleted User

    Deleted User

    Guest

  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,326
    Yeah using List<string> to store your words would make it much simpler to fetch individual words, add new ones or even shuffle the whole collection (in case you want to minimize repetition of words).

    I recommend you create a simple wrapper class for the list of words to make it more convenient to do common operations with it like fetching a random word from it.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections.Generic;
    3.  
    4. public class WordCollection
    5. {
    6.     private readonly List<string> words = new List<string>();
    7.  
    8.     public void AddWord(string word)
    9.     {
    10.         if(!words.Contains(word))
    11.         {
    12.             words.Add(word);
    13.         }
    14.     }
    15.  
    16.     public string GetRandomWord()
    17.     {
    18.         return words[Random.Range(0, words.Count)];
    19.     }
    20. }
    If you want to fetch your list of words from a text file you can use File.ReadAllLines to do it.