C# Random String from List

Hey all,

I’m new to this whole scripting, and I would love some help! I want to choose a random string from a list or array, but all of the method’s I’ve seen have led me in circles and errors. How would I do this? I’m using C# to script.

Thanks so much.

List yourStringList = new List();
string yourStringArray = new string[amountOfStrings];

// fill them

string randomListString = yourStringList[Random.Range(0, yourStringList.Count];
string randomArrayString = yourStringArray [Random.Range(0, yourStringArray .Length];

Not sure how previous methods have caused you issues here as it’s not too complex a problem, would be curious to see what errors other solutions were providing you. Here is a simple script that defines an array of strings in code, and an array that you can set in the inspector, and then a method to get a random item from either of those collections.

using UnityEngine;

public class RandomString : MonoBehaviour
    private string[] m_InspectorStrings;

    private string[] m_HardCodedStrings;

    void Awake()
        m_HardCodedStrings = new string[]
                "String Zero",
                "String One",
                "String Two",
                "String Three",
                "String Four",

    public string GetRandomInspectorString()
        return m_InspectorStrings[Random.Range(0, m_InspectorStrings.Length)];

    public string GetRandomHardCodedString()
        return m_HardCodedStrings[Random.Range(0, m_HardCodedStrings.Length)];