How to read/write text file?

Hello, I have tried finding this in the forum but failed,
If you could tell me how to read/write, create, and test the existence of a text file, i would appreciate it greatly. I know how to do this in Delphi and C#, but not in Javascript,
Thank you!

you can do it in C#

I have seen it in the feautures, but i would like to do it in javascript, as im trying to learn the language. Thanks for the reply.

There are some example scripts in the wiki that might help: http://www.unifycommunity.com/wiki/index.php?title=Scripts

http://www.unifycommunity.com/wiki/index.php?title=SimpleDictionary I’ve found this one to be particularly useful.

I have read that it is not possible to read/write to files, in javascript. They say however, that if you embed active x into your script? How can I make this work?

function WriteToFile()
{
var filename = “data.txt”;
var fso = new ActiveXObject(“Scripting.FileSystemObject”);
if (fso.FileExists(filename))
{
var a, ForAppending, file;
ForAppending = 8;
file = fso.OpenTextFile(filename, ForAppending, false);
file.WriteLine(name);
file.WriteLine(password);
}
else
{
var file = fso.CreateTextFile(filename, true);
file.WriteLine(password);
file.WriteLine(password);
}
file.Close();
}

function ReadFromFile()
{
var fso, a, ForReading;
ForReading = 1;
fso = new ActiveXObject(“Scripting.FileSystemObject”);
file = fso.OpenTextFile(filename, ForReading, false);
var name = file.readline();
var password = file.readline();
file.Close();
}

Thanks!! :slight_smile:

Sure it’s possible. Give the sample scripts in the wiki a try or buy one of the script utilities from Eric if you want a complete solution: starscenesoftware.com - starscenesoftware Resources and Information.

Can’t you just use the System.IO.File class in JavaScript?

System.IO.File.Exists(“C:\something.txt”);
System.IO.File.WriteAllText(“C:\something.txt”, “some text”);
var text : String = System.IO.File.ReadAllText(“C:\something.txt”);

Unless (given your question of using ActiveX) you’re looking to do this in a web browser, in which case all IO operations are blocked due to security reasons. The only way around it would be to employ some fancy browser communication to another browser plugin that does allow it. But honestly, you have to then question if this is necessary at that point. If you’re doing this just to allow users to save/load their games, look into the PlayerPrefs API instead.

Thank you all for the help, bit of tweaking with the simple dictionary, and I got it working great, I appreciate your help… Can’t believe the websites that said it is not possible with javascript. :slight_smile:

It’s not possible with actual website/HTML JavaScript. “JavaScript” in Unity is not actually JavaScript, it shares some base similarities with its syntax, but only a bit. It quickly diverges into its own language. That’s why some of us tend to refer to it as “UnityScript”.

Agreed, the first thing to do is not consider using Google Search for Unity JAvaScript related topics, cause you will get millions of browser JS responses and inbetween a few dozen for unity js

instead explicitely search here and answers.unity3d.com when it comes to Unity JS

Ah, very helpful, thank you very much. That is actually exactly what I have been doing, trying to find answers through google, but all it does is confuses.

Thank you!

Is there any possibility that you can share you insights? .)

Uhh there’s no reason to code in Unity with javascript for the purpose of “learning javascript”. Unity Javascript is not really comparable to microsoft jScript or traditional javascript from what I have seen. It’s a different language. I recommend you use c# because:

  1. Read/write to a file is easy, go to MSDN or pull up the local help files if you have Visual Studio.
  2. Things you learn about c# in Unity will be more 10,000x more beneficial to you outside Unity than Unity Javascript.

I have looked at the Microsoft sites and forum posts in here on the matter. But Im completely new to C# and my objective is to simply log x,y pos per 0.5 seconds to either an XML or txt file. I find it really difficult to declare ‘what’ and ‘how’ in the fileWrite scripts I have seen in these fora.

File Class (System.IO) | Microsoft Learn - File function

Check out the “File” and “FileStream” class and also, the System.IO namespace in general. It has useful classes for file operations.

Now I tried to write this code real quick as an example:

using UnityEngine;
using System.Collections;
using System.IO;  // using directive because file functions are here

public class write : MonoBehaviour {

    private float pos;
    string path; 
    void Start()
    {
        path = @"c:\log\log.txt";  //@ symbol so you don't have to escape your backslashes.
        pos = 500.0f;
        File.Create(path);

    }
	
	void Update () {

        if (File.Exists(path))
        {
            File.WriteAllText(path, pos.ToString() + "\r\n");  //give the path to the file, then convert your float to a str and add a line break.  :smile: 
        }
        
	}
}

It creates the file and writes to it, but gives a sharing violation and I don’t have time to figure out why. Just play around with the classes in System IO and find what you need.

@Krodil
If you still want to do it in javascript (sorry for the late reply) this is what I have learned,
you need an array to load the textfile into. so,

var arr=new Array();

then you need the following 2 procedures:

function Load( fileName : String ) //This 1 loads the file, line by line
{
i=0;
arr = new Array();
var counter = 0;
var offset : int;
var sr : StreamReader = new StreamReader ( Application.dataPath + “/” + fileName );
line = sr.ReadLine();
while (line != null)
{
Set(line); //Here it is sent to the set procedure to insert the new line into the array
line = sr.ReadLine();
}
sr.Close();

}

function Set(val : String )
{
arr =val;

  • i+=1;*
    }
    Its as simple as that…
    So to load the file, just call:
    Load(“Filename.txt”);
    Oh and also, unless you leave the file in you want to load in your assets, you need to set the file path. :slight_smile: Good luck!!

Thats true, but i already know C#, so it is fun to figure out this new language… Even if its not exactly like the real javascript. It does have its similarities… So im kinda learning a new language, and at the same time its great fun to learn it while making a game, also as there are so many similarities between C# and javascript, it’s quite easy to learn. Also, I am halfway through my project so no use changing to C# now! :slight_smile:

Hi all,
I have now one pice of working unity 2 xml file.
I have problems structuring my final xml. I mean I get this annoying ‘anytype’ which I have trouble finding a reason for.
Can I change it to something else, or do I have to live with it.

The attached files are the mainscript serializing.
The xml (packed) is the product

529209–18685–$XML.js (5.63 KB)
529209–18686–$test7.rar (330 Bytes)

bump. :slight_smile: