Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
3
Question by tperry1x · Oct 29, 2013 at 09:38 AM · specificreading

Read random line of external text file data into a variable (JS)

So, what I want to do is this: Read data from a file "data.txt". I want to then pick a random line of that data, say line 3. At the moment, I'm reading the whole file. Can I just read line 3 of that file?

var fileName = "data.txt";

 // read from filename
 var sr = new StreamReader(Application.dataPath + "/" + fileName);
 var fileContents = sr.ReadToEnd();
 sr.Close();
 
 // put data from filename into a variable
     // var mydata = fileContents.Split("\n"[0]);
             var mydata = fileContents;

     // pick a random number between 1 and 10
     var myrandom = Random.Range(1,10);

// I know this bit isn't right, but what I want is print (line myrandom of mydata);

It's in Javascript as that's more human-readable for me. I just can't get my head around C. Also, sorry I'm really new to all of this. I don't even know how to use tags on this website to show quoted code! :( Please help!!

Comment
Add comment · 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 Azrapse · Oct 29, 2013 at 10:37 AM 0
Share

All the answers you are going to get here involve reading all or part of the file, even if they return only the line you want. That's because there is no way to skip to line X in a text file without finding where all previous lines end first.

If you don't $$anonymous$$d that, then there is no problem with any of the answers you already got.

But if you really want a solution that doesn't scan the whole file in order to return a single line (for example, because doing so is extremelly slow, or you plan to read lines many times per second), you will need to request that clearly, because it would need a more efficient yet more complex solution.

avatar image vexe · Oct 29, 2013 at 10:42 AM 0
Share

Depending on your needs, my method could be more effective than ReadAllLines if you don't have a huge number of lines. Otherwise go with @EvilWarren's solution.

3 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by EvilWarren · Oct 29, 2013 at 10:04 AM

Almost there, but you commented out a line you really needed

 import System.IO;
 var fileName = "data.txt";
  
 function Start () {
 
      // read from filename
     var sr = new StreamReader(Application.dataPath + "/" + fileName);
     var fileContents = sr.ReadToEnd();
     sr.Close();
  
      // put data from filename into a variable
     var mydata = fileContents.Split("\n"[0]);
 
     // pick a random number between 1 and 10
     var myrandom = Random.Range(1,10);
     print(mydata[myrandom]);
 }

Important to make sure you have import System.IO there as well. Also, its convention to start indexing arrays at 0 so you might want to change the Random.Range to between 0 and 9.

Comment
Add comment · Show 6 · 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 vexe · Oct 29, 2013 at 10:14 AM 2
Share

Just to be safe:

 var myRandom = Random.Range(0, myData.Length);
avatar image EvilWarren · Oct 29, 2013 at 10:24 AM 0
Share

Good point, and you beat my slow fingers to an answer as well.

avatar image vexe · Oct 29, 2013 at 10:27 AM 0
Share

Small Q: When I'm doing an "import" or "using", formatting gets messed up. What you doing to keep it intact?

avatar image EvilWarren · Oct 29, 2013 at 10:39 AM 0
Share

Try taking an extra new line before your code sample. The code formatting doesn't seem very reliable so I treat it like a rabid dog and give extra space.

avatar image meat5000 ♦ · Oct 29, 2013 at 12:12 PM 0
Share

Thank you all for your answers. I've gone with EvilWarren's answer (as this was easiest for me to understand). I'm sure vexe's answer is correct too, and I like the idea of just reading a single line. I can't understand yet how to pass functions to scripts or whatever and where they need to go, what they need to be attached to and what files to make, so I've just gone with the simpler answer provided by EvilWarren. Thank you all though for your responses :)

@tperry1x Comment pasted here. It disappeared into the ether due to -1 Answers Bug

Show more comments
avatar image
2

Answer by vexe · Oct 29, 2013 at 10:02 AM

This does the job, quite good. It's tested. (Excuse my poor JS) - Just give it the file path, and the line number that you want. This does it without reading the whole file contents, and then picking up your line. I also wrote a GetNumberOfLines for convenience. Don't forget to include System.IO;

NOTE: if you want the first line of your file, you pass it a 0, for nLine, second, 1, etc - Just like indexing an array.

     [C#]
     string ReadLine(string path, int nLine)
     {
         string line = "";
         using (var reader = new StreamReader(File.Open(path, FileMode.Open))) {
            int n = 0;
            while (n++ <= nLine)
                line = reader.ReadLine();
         }
         return line;
     }

     int GetNumberOfLines(string path)
     {
         int nLines = 0;
         using (var reader = new StreamReader(File.Open(path, FileMode.Open))) {
             nLines = reader.ReadToEnd().Split('\n').Length;
         }
         return nLines;
     }

     [JS]
     function ReadLine(path : String, nLine : int) : String
     {
         var reader = new StreamReader(File.Open(path, FileMode.Open));
         var line : String = "";
         int n = 0;
         while (n++ <= nLine)
             line = reader.ReadLine();
         reader.Close();
         return line;
     }

     function GetNumberOfLines(path : String) : int
     {
         var reader = new StreamReader(File.Open(path, FileMode.Open));
         var nLines = reader.ReadToEnd().Split("\n"[0]).Length;
         reader.Close();
         return nLines;
     }

Test #1: Reads all the file, line by line

     var path = @"somewhere";
     var nLines = GetNumberOfLines(path);
     for (var i = 0; i < nLines; i++) {
          print (ReadLine(path, i));
     }

Test #2: Reads a random line in the file

     var path = @"somewhere";
     var nLines = GetNumberOfLines(path); 
     var rand = Random.Range(0, nLines);
     var randomLine = ReadLine(path, rand);
     print (randomLine);
Comment
Add comment · 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
0

Answer by dallasbrands · Nov 07, 2013 at 01:10 AM

I think I'm getting this, but I'm not sure how to use EvilWarren's example to post the random line of data somewhere else. Does anyone have any ideas? (I'm trying to get it to post onto a different PHP page.

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 Azrapse · Nov 07, 2013 at 05:54 AM 0
Share

That is a totally unrelated question. Reading a file for a particular line has nothing to do with what will you do later with the data you just read.

Create a new question.

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

20 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

Related Questions

Help with XML reading and writing 1 Answer

Apply force from specific location in space 0 Answers

movement 2d in a grid 3 Answers

How do I acces a specific GameObject within the terrain???? 1 Answer

Converting a String to Another Object's Boolean 1 Answer


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