Retrieving text file from the resources folder

I am at the end of project and being roadblock by one frustrating problem. I am just learning that unity cannot build with the UnityEditor namespace.

I am trying to write a text file to the resources folder, then set that text file to a TextAsset GameObject so I can use it later. Unfortunately without AssetDatabase.Refresh() the TextAsset is always null and won’t be found until the program is restarted.

Oddly, I have done this same process with a PNG and it works seamlessly. I can use System.IO to write and encode a PNG, then set it to a texture right away using Resources.Load();.

Why would it work for a PNG file, and not a TXT file? The print statement on line 17 even returns true.

Thanks so much for your help!

using UnityEngine;
using System.IO;
//using UnityEditor;

public class TextHandler : MonoBehaviour
{
    public TextAsset textFile;
    public string resourcesPath;
    void Start ()
    {
        resourcesPath = Application.dataPath + "/Resources/";
    }
    public void WriteTextFile(string NPCName, string NPCType, string NPCDialogue, string NPCItems)
    {
        System.IO.File.WriteAllText(resourcesPath + NPCName + "_" + NPCType + ".txt" , NPCDialogue + "~" + NPCItems + ".txt");
        //AssetDatabase.Refresh();
        print(File.Exists(resourcesPath + NPCName + "_" + NPCType + ".txt"));
        textFile = Resources.Load(NPCName + "_" + NPCType) as TextAsset;
    }

}

You shouldn’t be saving to the Resource folder anyways. Depending on your platform choice, some don’t even support writing anything to it. Use persistantDataPath to save stuff.

Thanks for the response. How would you load a TextAsset from persistantDataPath since Resources only loads from a folder named “Resources” anywhere in the Assets folder?

Using System.File.IO, read and write text files, not TextAssets, to Application.persistentDataPath.
How To: Write a Text File
How To: Read from a Text File

Thanks for the quick response TonyLi. I have explored that option as well. For my specific design purposes I actually need the object in the game as a TextAsset, not a string. Is that even possible? Can I create a new TextAsset assigned to a gameObject from the string?

I don’t think so. Assets are preprocessed into builds. Can you redesign the part that reads the TextAsset so it reads a text file instead?