- Home /
Question by
sudoman281 · Aug 06, 2017 at 03:36 PM ·
c#guieditoreditor-scriptingasset
Importing .png via script
Hello, I have a problem. When I try to import texture via script to my assets, I get this error:
Assertion failed: Assertion failed on expression: '!(o->TestHideFlag(Object::kDontSaveInEditor) && (options & kAllowDontSaveObjectsToBePersistent) == 0)'
UnityEditor.AssetDatabase:CreateAsset(Object, String)
Editor.TextureImportWindow:OnGUI() (at Assets/Scripts/Editor/TextureImportWindow.cs:40)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
and this:
Could not create texture from Assets/Textures/importedTexture13.png: File could not be read
UnityEditor.AssetDatabase:CreateAsset(Object, String)
Editor.TextureImportWindow:OnGUI() (at Assets/Scripts/Editor/TextureImportWindow.cs:40)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
My code:
public class TextureImportWindow : EditorWindow
{
[MenuItem("Window/Pixel Terrain/Import Texture")]
public static void ShowWindow()
{
GetWindow<TextureImportWindow>("Import Texture");
}
private Texture2D _texture;
private string _path;
private void OnGUI()
{
if (GUILayout.Button("Select File"))
{
_path = EditorUtility.OpenFilePanel("Choose texture", "", "png");
if (_path.Length != 0)
{
var www = new WWW("file:///" + _path);
_texture = Texture2D.blackTexture;
www.LoadImageIntoTexture(_texture);
}
}
if (_texture != null)
{
if (GUILayout.Button("Import"))
{
if (!AssetDatabase.IsValidFolder("Assets/Textures"))
{
AssetDatabase.CreateFolder("Assets", "Textures");
}
AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.png");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
}
Comment
Answer by jennybrown8 · Feb 10, 2020 at 02:39 AM
It's 2 years late, but in case someone lands here like I did... try changing this:
AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.png");
to use a .asset extension instead:
AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.asset");