Search code examples
c#unity-game-engineunity-editor

Unity Editor - From BinaryWriter to Object or TextAsset


Is there any way to retrieve the file that a BinaryWriter creates and turn it into a TextAsset or Object?

I'm creating a custom editor for my project, it has an option to create a new binary file: enter image description here

The field 'File' is for the user to drag an existing file, but the user can create a new one pressing the 'Create New File' button and ideally I would like the newly created file to be automatically placed in the field 'File'.

EDITED: As much as possible I would like to avoid saving the binary file to the resources folder and then load it and convert it to a TextAsset.

Thanks in advance!


Solution

    1. Save the new TextFile using BinaryWriter into the Resources Folder. (Create on in your Workspace, if there is none)

    2.a) Get the File as TextAsset via

     TextAsset textFile = (TextAsset)Resources.Load("myTextFile"), typeof(TextAsset));
    

    2.b) Alternatively, try this to load the recently-generated file:

    AssetDatabase.ImportAsset(path); // Update/Reload File in Unity
    TextAsset asset = Resources.Load("myTextFile");
    
    1. Assign textFile to the public variable File in your Custom Editor script.

    If you don't want a Resources Folder, try this:

    AssetDatabase.LoadAssetAtPath

    Note: AssetDatabase.Refresh() updates Unity's file catalogue, so I was wrong with ImportAsset. See comments below.