- Home /
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[i]);
}
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;
}
Comment
Answer by Artyom-Abgaryan · Apr 07, 2016 at 01:02 AM
@janzdott Use
orAssetDatabase.ImportAsset("Assets/image.png", ImportAssetOptions.ForceUpdate);
http://docs.unity3d.com/ScriptReference/AssetDatabase.Refresh.html