How to create a TextAsset in a ScriptedImporter?

I’m trying to write a ScriptedImporter (the new experimental feature) that can import a third party data format into JSON. I’ve got all my conversion code done and working great.

But when it’s time to implement the OnImportAsset() I’m stuck as to what I should provide to the ctx.SetMainAsset(). It’s expecting a UnityEngine.Object so I can’t just give it the string containing the JSON. So my assumption is that I should pass in a TextAsset, but its text field is read only and I have not found a way to instantiate a dynamic TextAsset by passing a string.

Should I use another asset type instead?

Unfortunately you can’t create “TextAsset” instances manually. So if you want to just store the information as a string / text you would need to wrap it in a simple ScriptableObject

public MyImportedType : ScriptableObject
{
    public string text;
}

MyImportedType inst = ScriptableObject.CreateInstance<MyImportedType>();
inst.text = yourJSONText;
// pass "inst" as asset.

I’m just wondering what type data format you’re reading in. Storing the result as JSON seems a bit strange to me as JSON is also just an intermediate format. For example when importing a model you should create a Mesh right away. If you import a graphic format you should create a Texture asset.

It seems you want to use the “ScriptedImporter” not as an importer but rather a simple file converter. Just converting a file may be done outside Unity and just import the converted result.

Of course you could simply create a new text file next to the original source file and write your content to that file. This will of course create an actual TextAsset but it’s of course seperate from the source file.

Thank you for your answer! Digging more last night I pretty much came to the same conclusion, which is fine really, and your answer helped me confirm this.

In fact that made me realize I may want to generate a ScriptedObject that is the final data object I’ll use in game. My source data can target different data structures, I’ve had the idea to use a convention in the filename that will dictate which data class to deserialize to.

Using your MyImportedType example, I could name my data file:

hardLevels.MyImportedType.xlsx

which would look for the middle part (MyImportedType) and through reflection I’d instantiate the proper ScriptedObject class to deserialize and save my main asset with.

Anyway, I’m getting off topic, thanks again for your answer!