Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Zachelle · Oct 07, 2015 at 05:59 AM · c#updatesstreamreader

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.");
                 }
 
             }
       
         }
       
     }
 }

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Oribow · Oct 07, 2015 at 02:19 PM 0
Share

You can set the stream reading postion back to zero to read from the start again.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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.

  • XYDemo.unitypackage

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);
     }
 }






Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Dalek_01 · Jan 04, 2016 at 05:32 AM 0
Share

Thanks :) ..

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

33 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges