How to constantly update the text file read by streamreader in real time?
Hello, I'm trying to read a text file in Unity which will contain constantly changing values (from another program) and to update this to my variables 'xpos' and 'ypos'.
So far I am able to read the file and assign it to my variables but it will only do it once and won't update. I think I have to add void update () somewhere but every time I try to put it somewhere, my originally working code comes up with errors everywhere.
What do I need to do?
Thanks
Here is the code so far
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.IO;
public class GetForce : MonoBehaviour
{
FileStream fs = new FileStream("input.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr;
public GetForce()
{
using(StreamReader sr = new StreamReader(fs))
{
string line;
int currentLineNumber = 0;
decimal xpos = 0;
decimal xposnew = 0;
decimal ypos = 0;
decimal yposnew = 0;
while (!sr.EndOfStream)
{
currentLineNumber++;
line = sr.ReadLine();
// Debug.Log(line);
try
{
switch (currentLineNumber)
{
case 1:
xpos = decimal.Parse(line);
Debug.Log("xpos = " + xpos);
break;
case 2:
ypos = decimal.Parse(line);
Debug.Log("ypos = " + ypos);
break;
}
}
catch (Exception ex)
{
Debug.Log("Error: " + ex.Message + ". Exiting.");
}
}
}
}
}
You can set the stream reading postion back to zero to read from the start again.
Answer by Statement · Oct 11, 2015 at 12:45 PM
Don't dispose the stream if you plan on reading the file again. You are using the using
statement which implicitly will call StreamReader.Dispose
when it exits scope. You can't use disposed objects so the next call to GetForce will fail.
I prepared an example that both writes and reads from disk.
To read from the beginning of the stream, you can call Stream.Seek. To empty contents of a stream you are writing, you can call Stream.SetLength. Using an invariant culture when parsing floats can be useful in case you pass files between computers that have different cultures. Some cultures format floats like 0.245 while others format floats like 0,245. Without an invariant culture, parsing can cause problems.
XYDemo.cs
using UnityEngine;
public class XYDemo : MonoBehaviour
{
// Change input.x and input.y in inspector
// Observe output.x and output.y in inspector
public Vector2 input;
public Vector2 output;
XYStreamWriter writer = XYStreamWriter.FromFile("input.txt");
XYStreamReader reader = XYStreamReader.FromFile("input.txt");
void Start()
{
// Intentionally not reading/writing to disk
// too often because I care about my hard drive.
InvokeRepeating("Write", 0.5f, 1.0f);
InvokeRepeating("Read", 1.0f, 1.0f);
}
void OnDestroy()
{
writer.Dispose();
reader.Dispose();
}
void Read()
{
print("Read...");
reader.Read();
output = reader.XY;
}
void Write()
{
print("Write...");
writer.XY = input;
writer.Write();
}
}
XYStreamReader.cs
using UnityEngine;
using System;
using System.IO;
using System.Globalization;
public class XYStreamReader : IDisposable
{
public Vector2 XY
{
get { return new Vector2(X, Y); }
private set { X = value.x; Y = value.y; }
}
public float X { get; private set; }
public float Y { get; private set; }
public bool IsDisposed { get; private set; }
private readonly Stream stream;
private readonly StreamReader reader;
private readonly CultureInfo culture;
public XYStreamReader(Stream stream)
{
culture = CultureInfo.InvariantCulture;
reader = new StreamReader(this.stream = stream);
}
public void Read()
{
if (IsDisposed)
throw new ObjectDisposedException("stream");
try
{
stream.Seek(0, SeekOrigin.Begin);
X = float.Parse(reader.ReadLine(), culture);
Y = float.Parse(reader.ReadLine(), culture);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void Dispose()
{
if (IsDisposed)
return;
stream.Dispose();
reader.Dispose();
}
public static XYStreamReader FromFile(string path)
{
Stream stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
return new XYStreamReader(stream);
}
}
XYStreamWriter.cs
using UnityEngine;
using System;
using System.IO;
using System.Globalization;
public class XYStreamWriter : IDisposable
{
public Vector2 XY
{
get { return new Vector2(X, Y); }
set { X = value.x; Y = value.y; }
}
public float X { get; set; }
public float Y { get; set; }
public bool IsDisposed { get; private set; }
private readonly Stream stream;
private readonly StreamWriter writer;
private readonly CultureInfo culture;
public XYStreamWriter(Stream stream)
{
culture = CultureInfo.InvariantCulture;
writer = new StreamWriter(this.stream = stream);
}
public void Write()
{
if (IsDisposed)
throw new ObjectDisposedException("stream");
try
{
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);
writer.WriteLine(X.ToString(culture));
writer.WriteLine(Y.ToString(culture));
writer.Flush();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void Dispose()
{
if (IsDisposed)
return;
stream.Dispose();
writer.Dispose();
}
public static XYStreamWriter FromFile(string path)
{
Stream stream = new FileStream(
path,
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.ReadWrite);
return new XYStreamWriter(stream);
}
}
Your answer
Follow this Question
Related Questions
Could..... not preload global game manager #0 i=0 1 Answer
Leave open a StreamReader in Unity c# 0 Answers
Loading JSON as a Text Asset using Resources.Load 1 Answer
Destructible Crate Problem 1 Answer
Save Data Android C# 0 Answers