Skip to content
The Chat Archive
gpt-4o-mini-2024-07-18· OpenAI WildChat-4.8M (AI2)

I have a Unity scene with thousands of gameobjects, meshes, materials & textures, all of…

  1. User

    I have a Unity scene with thousands of gameobjects, meshes, materials & textures, all of which are code generated and rendered into Unity. I need a c# Unity script that can batch export the entire scene into a folder and I also need it to be able to batch import everything back into place as it was, textures, materials, gameobjects, transforms, everything. Don't think simple scrap simple solutions.

  2. Assistant

    To create a comprehensive solution for batch exporting and importing the entire Unity scene with thousands of GameObjects, meshes, materials, and textures, you'll need to serialize all the required data into a format that can be easily saved to disk. Unity's ScriptableObject or JSON format could be useful here. Below is an example of how you might accomplish this using a C# Unity script.

    This implementation assumes you are comfortable using Unity's JsonUtility for serialization and that you're familiar with Unity's asset management system.

    Step 1: Define Serializable Objects

    Create classes that will hold the data you want to export/import.

    using UnityEngine;
    
    [System.Serializable]
    public class ExportData
    {
        public GameObjectData[] gameObjects;
    }
    
    [System.Serializable]
    public class GameObjectData
    {
        public string name;
        public Vector3 position;
        public Quaternion rotation;
        public Vector3 scale;
        public string prefabGUID; // To hold the reference to prefab in case of prefab usage
        public string meshGUID; // To hold the financial reference to the mesh
        public MaterialData[] materials;
    
        // Other properties such as layers, tags, etc. can be added here
    }
    
    [System.Serializable]
    public class MaterialData
    {
        public string name;
        public string shaderName;
        public TextureData[] textures;
    }
    
    [System.Serializable]
    public class TextureData
    {
        public string name;
        public string path; // Path to texture asset
    }
    

    Step 2: Create the Export Script

    Make a script that will handle the export process.

    using System.Collections.Generic;
    using System.IO;
    using UnityEditor;
    using UnityEngine;
    
    public class SceneExporter : MonoBehaviour
    {
        public string exportFolderPath = "Assets/ExportedScene";
    
        [ContextMenu("Export Scene")]
        public void ExportScene()
        {
            ExportData exportData = new ExportData();
            List<GameObjectData> gameObjectDataList = new List<GameObjectData>();
    
            foreach (var go in FindObjectsOfType<GameObject>(true)) // true to include inactive objects
            {
                GameObjectData goData = new GameObjectData
                {
                    name = go.name,
                    position = go.transform.position,
                    rotation = go.transform.rotation,
                    scale = go.transform.localScale
                };
    
                // Retrieve materials and textures
                List<MaterialData> materialsData = new List<MaterialData>();
                Renderer renderer = go.GetComponent<Renderer>();
                if (renderer != null)
                {
                    foreach (var mat in renderer.sharedMaterials)
                    {
                        MaterialData materialData = new MaterialData
                        {
                            name = mat.name,
                            shaderName = mat.shader.name,
                            textures = new TextureData[mat.GetTexturePropertyCount()]
                        };
    
                        for (int i = 0; i < mat.GetTexturePropertyCount(); i++)
                        {
                            string textureName = mat.GetTextureName(i);
                            Texture texture = mat.GetTexture(textureName);
                            if (texture != null)
                            {
                                string assetPath = AssetDatabase.GetAssetPath(texture);
                                materialData.textures[i] = new TextureData { name = textureName, path = assetPath };
                            }
                        }
    
                        materialsData.Add(materialData);
                    }
                }
    
                goData.materials = materialsData.ToArray();
                gameObjectDataList.Add(goData);
            }
    
            exportData.gameObjects = gameObjectDataList.ToArray();
            string json = JsonUtility.ToJson(exportData, true);
    
            // Create folder if it doesn't exist
            if (!Directory.Exists(exportFolderPath))
            {
                Directory.CreateDirectory(exportFolderPath);
            }
    
            // Save to a file
            File.WriteAllText(Path.Combine(exportFolderPath, "sceneExport.json"), json);
            AssetDatabase.Refresh();
        }
    }
    

    Step 3: Create the Import Script

    Make a script that handles restoring the exported scene.

    using System.Collections.Generic;
    using System.IO;
    using UnityEditor;
    using UnityEngine;
    
    public class SceneImporter : MonoBehaviour
    {
        public string importFilePath = "Assets/ExportedScene/sceneExport.json";
    
        [ContextMenu("Import Scene")]
        public void ImportScene()
        {
            if (!File.Exists(importFilePath))
            {
                Debug.LogError("Import file does not exist!");
                return;
            }
    
            string json = File.ReadAllText(importFilePath);
            ExportData importData = JsonUtility.FromJson<ExportData>(json);
    
            foreach (var goData in importData.gameObjects)
            {
                GameObject newGO = new GameObject(goData.name);
                newGO.transform.position = goData.position;
                newGO.transform.rotation = goData.rotation;
                newGO.transform.localScale = goData.scale;
    
                // Handle Materials and Textures loading
                if (goData.materials != null)
                {
                    Renderer renderer = newGO.AddComponent<MeshRenderer>();
                    List<Material> materials = new List<Material>();
    
                    foreach (var matData in goData.materials)
                    {
                        Material material = new Material(Shader.Find(matData.shaderName));
    
                        foreach (var texData in matData.textures)
                        {
                            if (!string.IsNullOrEmpty(texData.path))
                            {
                                Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(texData.path);
                                if (texture != null)
                                {
                                    material.SetTexture(texData.name, texture);
                                }
                            }
                        }
    
                        materials.Add(material);
                    }
    
                    renderer.sharedMaterials = materials.ToArray();
                }
            }
    
            Debug.Log("Import complete!");
        }
    }
    

    Usage Information:

    1. Exporting the Scene:

      • Attach SceneExporter to a GameObject in your scene.
      • Call the method ExportScene() from the Unity inspector context menu.
    2. Importing the Scene:

      • Attach SceneImporter to a GameObject in your scene.
      • Call the method ImportScene() from the Unity inspector context menu.

    Important Notes:

    • This script handles basic exporting and importing of GameObject transforms, materials, and textures. You may expand it with additional properties like particle systems, meshes, etc., depending on your needs.
    • The script assumes your materials use standard Unity shaders. Custom shaders may need additional handling.
    • The paths used to save and read files can be adjusted based on your project structure.
    • Make sure to test the script in a backup scene or a testing environment to avoid data loss.
    • The methods used can take some time to execute based on the number of GameObjects, so consider running them in a separate thread if you have large numbers of GameObjects.