- Home /
"Save As..." Saving level assets at Runtime
I'm making a run-time level editor for myself. I've created a grid and tile editing tool, but am struggling with saving the level data. From reading the Unity tutorials, I am trying the most "Unity-esque" approach: Making my level object a ScriptableComponent, and saving/loading it as an Asset using AssetDatabase
My problem is creating a "Save As..." function. Here is the current code in my LevelEditor class which runs when the user clicks the "Save" button:
string filePath = EditorUtility.SaveFilePanelInProject("Save level",
"level",
"asset",
"Save the level");
AssetDatabase.CreateAsset(level, filePath);
AssetDatabase.SaveAssets();
The problem is this code only works for one click. The first time I click, it opens the file explorer for me to pick where to save the file, creates the asset and saves it there. However, If I click save a second time, I get the following error (Regardless of the file path chosen):
Couldn't create asset file because the MonoBehaviour 'level' is already an asset at 'Assets/Levels/level.asset'!
UnityEditor.AssetDatabase:CreateAsset(Object, String)
I think this is because even though I might be saving the ScriptableObject in a different folder or with a different asset name, Unity still has that particular level object loaded in memory from the first save as an existing asset. Is there a way to to somehow detach or unbind the level object from the asset, or "unload" the asset information so it can be saved again as a different file? I have search the API and Manual but can't seem to find much info on this.
Did you ever find the solution to this problem? I'm having the same issue.