Get random line from text file

  • Thread starter Thread starter momofhfaboy728013
  • Start date Start date
M

momofhfaboy728013

Guest
I just decided to learn game dev about 3-4 months ago and mostly started following tutorials on YouTube and googling whatever questions that I had. I don't have a background or previous education or experience with any of it, so it can be confusing. I have a working piece of code that I spliced together from 2 different codes, it works, but I'd like it to work slightly differently. I spliced together a typewriter code and a text reader code, so as of now, the code below works as follows: It gets the entire text of the text file and writes it the UI textbox and therefore displays up to the first 3 lines of the text file that the size of the UI panel will allow. What I have tried with no success is for some way to make it so that only 1 random line of the text file will be displayed whenever the player accesses the scene. Here is what I have, thanks in advance for any guidance on the subject. This is for Unity and C#.

using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System;
using UnityEngine;
public class FactGenerator : MonoBehaviour
{
public Text text;
public TextAsset textFile;
public bool playOnAwake = true;
public float delayToStart;
public float delayBetweenChars = 0.075f;
public float delayAfterPunctuation = 0.0025f;
private string story;
private float originDelayBetweenChars;
private bool lastCharPunctuation = false;
private char charComma;
private char charPeriod;
public List<string> facts;
public string[] lines;
void Awake()
{
text = GetComponent<Text>();
originDelayBetweenChars = delayBetweenChars;
charComma = Convert.ToChar(44);
charPeriod = Convert.ToChar(46);
if (playOnAwake)
{
ChangeText(text.text, delayToStart);
}
}
public void ChangeText(string textFile, float delayBetweenChars = 0f)
{
StopCoroutine(PlayText()); //stop Coroutine if exist
story = Resources.Load<TextAsset>("dinofacts").text;
text.text = ""; //clean text
Invoke("Start_PlayText", delayBetweenChars); //Invoke effect
}
void Start_PlayText()
{
StartCoroutine(PlayText());
}

IEnumerator PlayText()
{
foreach (char c in story)
{
delayBetweenChars = originDelayBetweenChars;
if (lastCharPunctuation)
{
yield return new WaitForSeconds(delayBetweenChars = delayAfterPunctuation);
lastCharPunctuation = false;
}
if (c == charComma || c == charPeriod)
{
lastCharPunctuation = true;
}
text.text += c;
yield return new WaitForSeconds(delayBetweenChars);
TextAsset factText = Resources.Load<TextAsset>("dinofacts");
lines = textFile.text.Split("\r\n"[0]);

bool addingFacts = true;
for (int i = 0; i < lines.Length; i++)
{
if (lines == "facts:")
{
addingFacts = true;
Debug.Log("adding facts");
continue;
}
if (lines != "")
{
if (addingFacts)
{
facts.Add(lines);
}
}
}
}
}
}

Continue reading...
 
Back
Top