Creating An XML TextAsset when Importing Textures

I’m trying to write an editor script which creates an XML file to go with certain textures. I want the resulting file as an asset in the asset database. Is this possible?

My script so far is this:

public class ImageImporter : AssetPostprocessor 
{
    void OnPreprocessTexture()
    {
        if (assetPath.Contains("_ImageImport")==true)
        {
            
            TextureImporter TI = assetImporter as TextureImporter;
            TI.isReadable = true;
            char[] suffix = new char[4] {'.','t','g','a'};
            TextAsset TA = new TextAsset();
            AssetDatabase.CreateAsset(TA, assetPath.TrimEnd(suffix) + ".xml");
            
        }
    }

}

Unfortunately, no asset is created and I get a bunch of null object violations in System.Reflection.Binder instead. Perhaps I’m going about things the wrong way, but I simply want to analyze incoming textures, and write the data to an XML file which is part of the asset database (maybe I’ll add more stuff and make it a prefab).

I tried AssetDatabase.SaveAssets() too but it made no difference, and also crashed.

You could use AssetDatabase.LoadAssetAtPath(path, typeof(Texture)); in order to load the texture asset into a texture var.

Edit: sry didnt see it was in preprocess you probably cant use that then.

//perlohmann

That’s not a bad idea though. I’d have to do it a bit differently, but it still might work. Ideally I would have liked to either have it done on import or have it available on the right click menu in the scene hierarchy, but if neither of those are possible, what you suggest might be the best remaining way.

Thanks.

XML files automatically become TextAssets during their own import process. The interface to a TextAsset is read-only, anyway. What you’ll want to do is create an XML file via the System.IO .NET classes in a normal way.

If you dont want to do anything pre importing then you might want to do it in the: OnPostprocessTexture (Texture2D, texture) function instead. And yea you can just create an XML file via system.io.file.create(path).

If you dont see your xml file in the project window untill you tab out and back into the editor you can use AssetDatabase.Refresh() to force the editor project window to refresh.

//perlohmann