Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
2.2 kB
4
Indexable
Never
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System;

public class levelbuilder : MonoBehaviour
{
    public prefabIndexer assetLibrary; 
    private Dictionary<GameObject, GameObject> instanceToPrefabMap = new Dictionary<GameObject, GameObject>();

    [Serializable]
    public struct SceneObjectData
    {
        public string name;
        public uint id;
    }



    public void ExportSceneObjectData()
    {
        List<SceneObjectData> sceneObjectDataList = new List<SceneObjectData>();

        // Move the instantiation of prefabs here
        foreach (var asset in assetLibrary.index.Values)
        {
            GameObject prefab = Instantiate(asset); 
            instanceToPrefabMap[prefab] = asset; 
            prefab.SetActive(false); 
        }

        // Iterate through all GameObjects in the scene
        foreach (var obj in FindObjectsOfType<GameObject>())
        {
            GameObject originalPrefab;
            if (instanceToPrefabMap.TryGetValue(obj, out originalPrefab))
            {
                uint id = GetCustomID(originalPrefab);

                if (id != 0)
                {
                    SceneObjectData sceneObjectData = new SceneObjectData
                    {
                        name = obj.name,
                        id = id
                    };

                    sceneObjectDataList.Add(sceneObjectData);
                }
            }
        }


        string json = JsonUtility.ToJson(new SceneObjectDataArray { DataList = sceneObjectDataList }, true);


        string filePath = Application.dataPath + "/scene_objects.json";
        File.WriteAllText(filePath, json);

        Debug.Log("Scene object data saved to " + filePath);
    }

    [System.Serializable]
    private struct SceneObjectDataArray
    {
        public List<SceneObjectData> DataList;
    }


    private uint GetCustomID(GameObject obj)
    {
        uint id = 0; 

        prefabIndexer.IndexedAsset asset = obj.GetComponent<prefabIndexer.IndexedAsset>();
        if (asset.id != 0)
        {
            id = asset.id;
        }

        return id;
    }
}