How should I save/load file in Unity at runtime? (what the proper way)

In short words:

When should I use simple StreamWriter and StreamReader only for file-IO operations? And when I should use AssetDatabase stuff for for this purpose?

In more) words:

I’m new to Unity. All I need now - to save some txt-data to file, when user push “save” button in my Unity editor extension. And be able to load it back by “Load” button.
I’ve used StreamWriter for saving:

static void WrieStringToFile(string myString, string fileNameWithFullPath)
{
    // I even don't need this block - looks like `StreamWriter` handles file creation 
    // .. (if needed) by himself:
    // if (!System.IO.File.Exists(fileNameWithFullPath))
    //     System.IO.File.Create(fileNameWithFullPath);

    StreamWriter sw = new StreamWriter(fileNameWithFullPath);
    try
    { sw.Write(myString); }
    catch (Exception err)
    { Debug.LogError("Error saving file: " + err.Message); }
    sw.Close();
}

, and it works. And, I hope, there should not be any problems with loading data from such file using StreamReader. But, now I’ve encountered another way to work with file in Unity - something like this:

MyType assetObj = new MyType();
AssetDatabase.CreateAsset(assetObj, assetNameWithFullPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();

// Same logic, as I've used without all these wrappers of AssetDatabase stuff
// (but I'm not sure, I saw the proper code in this part - may be saving should 
// .. be also some AssetDatabase-operation, but I didn't find any similar)
WrieStringToFile(myString, assetNameWithFullPath);

EditorUtility.SetDirty(assetObj);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();

If I understand correct, this “with AssetDatabase stuff” approach stores data structured by MyType. In other words, the asset looks like MyType instance, stored to hard drive. And it lets me load data from such file directly in MyType instance by

MyType assetObj = AssetDatabase.LoadAssetAtPath<MyType>(assetNameWithFullPath);

(without need of parsing data, as it is in my 1st (used) case of simple txt-file).
So, I assume, I should use AssetDatabase for file-IO operations if I need provided by it “some-game-object to asset (it is stored to) and backwards easy data transfer interface”. Otherwise simple 1st mentioned in this topic approach is enough. Am I right?

Did I understand the gist of 2nd approach correct?
And please, help me to clarify the question: in what cases should be used each of these 2 approaches?

@SaSha_K As I remember, “AssetDatabase.CreateAsset” and “AssetDatabase.SaveAssets” only work on Editor, so you can’t use in runtime.


documentation seems is not clarifying this (Unity - Scripting API: AssetDatabase.SaveAssets)


Check this following answer, I think they are achieving you want by using “Streaming Assets”

(Proper way to save ScriptableObjects changed during play mode - Questions & Answers - Unity Discussions)