Create .png file from script, then import as asset

So I wrote this method for an editor script. It saves a Texture2D as a .png file, then tries to import the .png file as an asset. But I can’t figure out how to import the newly created .png file. And yes, I’m saving the .png file in the assets folder. Any ideas?

using System.IO;

Texture2D SaveTexture(Texture2D texture, string filePath) {
        byte[] bytes = texture.EncodeToPNG();
        FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        BinaryWriter writer = new BinaryWriter(stream);
        for (int i = 0; i < bytes.Length; i++) {
            writer.Write(bytes*);*

}
writer.Close();
stream.Close();
DestroyImmediate(texture);
//I can’t figure out how to import the newly created .png file as a texture
AssetDatabase.Refresh();
Texture2D newTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(filePath, typeof(Texture2D));
if (newTexture == null) {
Debug.Log(“Couldn’t Import”);
}
else {
Debug.Log(“Import Successful”);
}
return newTexture;
}

1 Answer

1

@janzdott
Use

AssetDatabase.ImportAsset(“Assets/image.png”, ImportAssetOptions.ForceUpdate);
or
Unity - Scripting API: AssetDatabase.Refresh