How to set a texture resource to texture type "GUI" by script?

Using the editor, I can select a texture asset (PNG file) and set its “texture type” to “GUI” manually. This allows it to be displayed pixel-perfect in the UI.

My game generates PNG files automatically (saved in the resources folder) that are then displayed in the UI. So it needs to load these at runtime with texture type “GUI” instead of the default “texture”.

So how can you set the texture type of assets through scripting?

You can set the guitexture directly without saving as png doing this …

 var tex = new Texture2D(1, 1);
    tex.SetPixels(new Color[] {Color.white});
    tex.Apply();
    style.normal.background=tex;

Or you can change import settings

var bytes=tex.EncodeToPNG();
string path="Assets/Resources/... .png";
File.WriteAllBytes(path,bytes);
AssetDatabase.Refresh();
AssetDatabase.ImportAsset(path);
TextureImporter importer = AssetImporter.GetAtPath(path)as TextureImporter;
importer.textureType=TextureImporterType.GUI;
AssetDatabase.WriteImportSettingsIfDirty(path);