Saving game obj from gameplay as prefab?

When I click play, how can I save a generated obj into my assets folder? so that it’s there when I stop the game?

Pause the game and drag from the hierarchy view to the project view.

I have a scene where it generate a mesh cave (like the unity tutorial) and I want to save the cave, but when I drag it in, it doesnt save the mesh

Here is how I do it:

using UnityEngine;
using UnityEditor;



public class SaveMesh {


     
   [MenuItem("Tools/Save Mesh")]
   private static void DoIt(){
      GameObject obj = Selection.activeGameObject;
      if(obj==null){
         Debug.LogError("You must select a GameObject in order to save its mesh.");
         return;
      }
      MeshFilter   mfl = obj.GetComponent<MeshFilter>();
      Mesh         msh = Mesh.Instantiate(mfl.sharedMesh);
#if !UNITY_5_5_OR_NEWER
      msh.Optimize();
#endif
      AssetDatabase.CreateAsset(msh,"Assets/Meshes/"+obj.name+".asset");
      AssetDatabase.SaveAssets();
   }
  
  
}

This will add a “Tools” submenu you just select the GameObject that contains the mesh, and select “Save Mesh”.

where is the menu located? I added this script to a empty game object and I dont see menu

No, don’t add it to a game object. I forgot to tell you, you have to save it into a folder named “Editor” inside your “Assets” folder.

for more info, read this:

getting error: Parent directory must exist before creating asset at Assets/Meshes/Walls.asset.
the mesh I want to get is a child object that have meshfilter, and the parent object is just an empty gameobj that hold the script to generate the cave mesh

using UnityEngine;
using UnityEditor;
using System.Collections;

public class Savemesh : EditorWindow {

    [MenuItem("Tools/Save Mesh")]
    private static void DoIt()
    {
        GameObject obj = Selection.activeGameObject;
        if (obj == null)
        {
            Debug.LogError("You must select a GameObject in order to save its mesh.");
            return;
        }
        MeshFilter mfl = obj.GetComponent<MeshFilter>();
        Mesh msh = Mesh.Instantiate(mfl.sharedMesh);
#if !UNITY_5_5_OR_NEWER
        msh.Optimize();
#endif
        AssetDatabase.CreateAsset(msh, "Assets/Meshes/" + obj.name + ".asset");
        AssetDatabase.SaveAssets();
    }
}

nvm, didnt make a meshes folder lol, how would I edit it so that it saves multiple selections?