Create a Textasset from a string

Hello :slight_smile:

The goal of my editor script is to create a Textasset containing the string I give it.
At the moment, I do the following:
Create a .txt file in Assets/Resources containing the text
Then make it a textasset using:

(TextAsset)Resources.LoadAssetAtPath(myfile,typeof(TextAsset))

But it returns null if the Textfile is created above in the code, just like the textfile isn’t finished yet (I closed the stream, I triplechecked this)
However, it works if the textfile was here before the script started. (and the TextAsset.text has the value of the string in the text BEFORE the script is executed (I’m not sure if i’m clear in the explanation…)

Lets make an example:
I want to write “ABC” in my asset.

if the file does not exists, my asset is null.

if the file exists and contains “123” after the execution of my script the TextAsset.text will be 123, but the file on my disk will have “ABC”.

Is it clearer like this ? :confused:

You’re all thinking too hard. Just do:

        File.WriteAllText(Application.dataPath + "/test.text", "blabla"));
        AssetDatabase.Refresh();

How did you create the text file?

You need to use AssetDatabase.CreateAsset and an object of type TextAsset.

Try something like:

TextAsset text = new TextAsset();
AssetDatabase.CreateAsset(text, "Assets/MyText.txt");

Also, don’t forget to commit any change using AssetDatabase.SaveAssets.

text.text = "my text content";
AssetDatabase.SaveAssets();

edit: for some obscure reasons, TextAsset.text is read-only. The above code will not work.

In that case, try to refresh the database before creating the TextAsset, using AssetDatabase.Refresh. It is worth to note that Unity Editor only works with cached assets not with the real asset files on disk.

TextAsset ConvertStringToTextAsset(string text) {
string temporaryTextFileName = “TemporaryTextFile”;
File.WriteAllText(Application.dataPath + “/Resources/” + temporaryTextFileName + “.txt”, text);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
TextAsset textAsset = Resources.Load(temporaryTextFileName) as TextAsset;
return textAsset;
}

This is a complete solution for how I tried to solve this. As mentioned in Kryptos’s comment AssetDatabase can be used only in editor, not in builds. I asked for a solution for builds in #unity3d irc channel and was told that there is no way to create TextAssets on the fly in builds.

in JS… THIS WORKS!:slight_smile:

import System.IO;

function writeStuffToFile(){
var stuff : String = “stuff”;
File.WriteAllText(Application.dataPath +“/stuff.txt”,stuff);
}

function readStufFromFile(){
var stuff : String;
stuff = File.ReadAllText(Application.dataPath +“/stuff.txt”);
Debug.Log(stuff);
}