Random word from text file c#

I’m working on an app for my daughter and I’m freakin’ dying over hear. I’ve been learning to code, so I’m not quite versed enough to figure this out. I’ve searched, watched tutorials, etc.

I have a simple text file called word list. I want to split it by line (
) and then pick a random word, then pass that word on to my TextToSpeech class.

I love figuring this stuff out on my own, but I’m getting dangerously delirious. LOL. Can someone please show me the right way to write this? I would love you forever!!

Here is my current code that obviously does not work. I cant get the random word part right.

using UnityEngine;
using System.Collections;

public class GuiSampleController : MonoBehaviour {

	public TextAsset WordList;

	 string WordToSpeak = WordList.text.Split('

');
int MyRandom = Random.Range (1,101);

	void Start ()
	{

			TextToSpeechManager.SendTextToSpeech(WordToSpeak[MyRandom]);
		}
	}

Ok. I finally got it.

using UnityEngine;
using System.Collections;

public class textNewSpeaker : MonoBehaviour {

	public TextAsset textFile;

	string[] dialogLines;
	
	void Start ()
	{
		if(textFile != null)
		{
			dialogLines = ( textFile.text.Split( '

’ ) );
string dialog = dialogLines[Random.Range(0,100)];

			TextToSpeechManager.SendTextToSpeech(dialog);
			//GetComponent<TextMesh>().text = dialog;
		}
	}
}

`

Rather than do
string dialog = dialogLines[Random.Range(0,100)];
You should so string dialog = dialogLines[Random.Range(0,dialogLines.Length)];.

The .Length part makes the array as big as how many values are in your document. In your instance if you have any thing less than 100 values in your document nothing will be displayed. Using .Length ensures the Random.Range function will only choose a number which has a value.

For example if your document has only 20 lines in it but Random.Range gets the number 58 then nothing will be displayed as their isn’t a 58 value/line. Adding the dialogLines.Length part means the max number can only be the max value amount of values in your document.

Unity may sometimes change your .Length to .Count. That is fine. They both work.

I know this question is old but i wanted to add this in case somebody else is having this issue.

Looks like you want WordToSpeak to be an array of strings
string[] WordToSpeak

In the future, bear in mind we’d like to hear any specific error messages you get to help us help you. Best of luck,