• 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 /
avatar image
Question by SpaceSocks · Nov 27, 2014 at 03:04 AM · fileiotext file

Help with StreamReader / Reading Text File

Hey guys,

So I've found lots of examples about reading / writing to text files. I tried to figure t$$anonymous$$s out myself but I'm still new to C#

making an RPG game and I'm storing the game characters attributes in a text file. I was able to figure out how to store them line by line but I'm having troubles figuring out how to read each line of the text file and then assigning each line to a variable. some of them will need to be strings but most ints.

here is an example of how i stored the variables to a text file:

   File.AppendAllText (usersPath, playerHealth + Environment.NewLine);
   File.AppendAllText (usersPath, playerMana + Environment.NewLine);
   File.AppendAllText (usersPath, playerStrength + Environment.NewLine);
   File.AppendAllText (usersPath, playerDex + Environment.NewLine);

whats the easiest way to read each line and store that line to a var?

I'm assuming i can use file.ReadAllText or I'd have to use System.IO.StreamReader?

Thanks for any help.

Comment

People who like this

0 Show 2
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 gjf · Nov 27, 2014 at 10:10 AM 0
Share

if you don't need to store much text, you can save it in player prefs - look at this for more info.

if you really want to use the file system then you could use ReadAllText or something from the StreamReader, but you'll need to parse the input which could be a can o' worms.

saving as plain text would work, but you'd be better served in the long run by spending some time familiarizing yourself with JSON. the interwebs have many c# examples of both, and unity has some free plugins too - check out the asset store.

avatar image SpaceSocks · Nov 27, 2014 at 10:39 PM 0
Share

The reason why I even tried it the way i did is because i grew up using QBASIC in DOS... so I have never known another way. :)

1 Reply

· Add your reply
  • Sort: 
avatar image

Answer by Cherno · Nov 27, 2014 at 02:56 PM

The only example I could find in my projects is from a script I found on the net, maybe it can help you understand what's possible when readin a text file.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 
 public class WriteToFile : MonoBehaviour
 {
     private Color varToGet;
     private Color varToGet2;
     private TextAsset textFileVar;
     private string textFileToString;
 
 
 
 
 
     void Awake() {
         textFileVar = Resources.Load("Scripts/blubb") as TextAsset;
 
 
     }
 
     void Start() {
         Main ();
         textFileToString = textFileVar.text;
         var stringToDic = ParseColorTable(textFileToString);
         varToGet = stringToDic["skinColor"];
         varToGet2 = stringToDic["hairColor"];
     }
 
     public static void Main() {
         // Create an instance of StreamWriter to write text to a file.
         // The using statement also closes the StreamWriter.
         using (StreamWriter sw = new StreamWriter("Assets/Resources/Testfiles/TestFile.txt")) {
             Debug.Log ("writing to file");
             // Add some text to the file.
             sw.Write("T$$anonymous$$s is the ");
             sw.WriteLine("header for the file.");
             sw.WriteLine("-------------------");
             // Arbitrary objects can also be written to the file.
 
 
 
 
         }
         System.IO.File.AppendAllText("Assets/Resources/Testfiles/TestFile.txt", System.String.Format("{0} {1} {2} {3} {4}", "string1", "string2", "float1", "float2", "float2"));
     }
 
     Dictionary<string, Color> ParseColorTable(string aText)    {
         
         Dictionary<string, Color> result = new Dictionary<string,Color>();
         
         string[] lines = aText.Split('\n');
         foreach (string L in lines)    {
             if (L.StartsWith("RGBA(")) {
                 // Cut "RGBA(" and split at ")"
                 string[] S = L.Substring(5).Split(')');
                 
                 // Remove all spaces and split the 4 color values
                 string[] values = S[0].Replace(" ","").Split(',');
                 
                 // Parse the 4 strings into floats and create the color value
                 Color col = new Color(float.Parse(values[0]),float.Parse(values[1]),float.Parse(values[2]),float.Parse(values[3]));
                 
                 // Read the colorname and remove leading or trailing spaces
                 string colorName = S[1].Trim();
                 
                 result.Add(colorName,col);
             }
         }
         return result;
     }
 
 
     Dictionary<string, Color> ParseFillTable(string aText)    {
 
         Dictionary<string, Color> result = new Dictionary<string,Color>();
         
         string[] lines = aText.Split('\n');
         foreach (string L in lines)    {
             if (L.StartsWith("RGBA(")) {
                 // Cut "RGBA(" and split at ")"
                 string[] S = L.Substring(5).Split(')');
                 
                 // Remove all spaces and split the 4 color values
                 string[] values = S[0].Replace(" ","").Split(',');
                 
                 // Parse the 4 strings into floats and create the color value
                 Color col = new Color(float.Parse(values[0]),float.Parse(values[1]),float.Parse(values[2]),float.Parse(values[3]));
                 
                 // Read the colorname and remove leading or trailing spaces
                 string colorName = S[1].Trim();
                 
                 result.Add(colorName,col);
             }
         }
         return result;
     }
 }
 
Comment
Taszty

People who like this

1 Show 0 · 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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

27 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

Related Questions

OBB. How I can access files in OBB? 0 Answers

Unity not properly flushing file output? 0 Answers

Create Text File 3 Answers

parsing csv file 2 Answers

Search for files on android 2 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