I’ve been looking for a good method of writing and reading from an external .txt file to create a scavenger hunt list.
The idea is that if you say you are looking for an item: Example:
“we are looking for a giant rubber spider”
Then that information would somehow be saved into a .txt file to be read back in later.
If you were to say:
“We are looking for a witches hat”
That too would be saved in a list format to the same .txt file.
Now here is where it might get tricky.
If you say we have found the rubber spider then that item gets removed from the .txt file.
The list would also need to be displayed when called upon as a UI Text list that would update automatically based on what is currently in the .txt file.
Has anyone done something like this?
Maybe something like this?:
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace Assets
{
public class TextHandler
{
// Enter the path of the file here
private string filePath = "";
private List<string> _fileLines;
private List<string> FileLines
{
get
{
if (_fileLines != null) return _fileLines;
string text = File.ReadAllText(filePath);
if (string.IsNullOrEmpty(text))
{
// Make empty list
_fileLines = new List<string>();
}
else if (!string.IsNullOrEmpty(text) && text.Any(f => f.Equals(',')))
{
// Read text and split on comma
_fileLines = text.Split(',').ToList();
}
else
{
// Read lines instead
_fileLines = File.ReadAllLines(filePath).ToList();
}
return _fileLines;
}
set
{
_fileLines = value;
File.AppendAllText(filePath, string.Join(",", _fileLines.ToArray()));
}
}
/// <summary>
/// Retrieve all up to date lines
/// </summary>
/// <returns></returns>
public List<string> GetAllLines()
{
return File.ReadAllText(filePath).Split(',').ToList();
}
/// <summary>
/// Remove existing line from file if it exists
/// </summary>
/// <param name="line"></param>
public void RemoveLine(string line)
{
// Remove line
FileLines.Remove(line);
// Save file
File.AppendAllText(filePath, string.Join(",", _fileLines.ToArray()));
}
public void AddLine(string line)
{
// Add line
FileLines.Add(line);
// Save file
File.AppendAllText(filePath, string.Join(",", _fileLines.ToArray()));
}
}
}