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();
}
}
}
}
First of all, AssetDatabase.CreateAsset
supports few extensions and png is not one of them. According to the doc, these are the supported formats:
.mat
for materials.cubemap
for cubemaps.GUISkin
for skins.anim
for animations.asset
for arbitrary other assets.)PNG is not mentioned anywhere so you get error when you try to import it with that function. AssetDatabase.ImportAsset
is more appropriate for this but since it requires a relative path, it won't work because you are using an absolute path provided from EditorUtility.OpenFilePanel
.
To import png file into your project from EditorUtility.OpenFilePanel
, just copy it to the destination with File.Copy
or FileUtil.CopyFileOrDirectory
(Recommended) then call AssetDatabase.Refresh()
.
Replace:
AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.png");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
with:
FileUtil.CopyFileOrDirectory(_path, "Assets/Textures/importedTexture12.png");
AssetDatabase.Refresh();