Esempio n. 1
0
 private void OnGUI()
 {
     TestJSON.TestClass testClass = new TestJSON.TestClass
     {
         variable = 1,
         property = 2
     };
     testClass.ints.Add(1);
     testClass.ints.Add(2);
     testClass.dic["hello"] = 1;
     testClass.dic["mum"]   = 2;
     testClass.intar[0]     = 99;
     testClass.ar[0]        = testClass.ints;
     testClass.ar[1]        = testClass.dic;
     testClass.md[1, 1]     = 1000;
     if (GUILayout.Button("Press me", new GUILayoutOption[0]))
     {
         JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testIt.json", "testserializer", "T3sts3rializer", delegate(Exception error)
         {
             Debug.Log(base.transform.position.ToString());
         });
     }
     if (GUILayout.Button("Or me", new GUILayoutOption[0]))
     {
         LevelSerializer.LoadSavedLevelFromFile("test.data");
     }
 }
Esempio n. 2
0
    /// <summary>
    /// Load a game from a provided string
    /// </summary>
    /// <param name="save"> Serialization string of the saved gameObject</param>
    public static void LoadFromString(string save)
    {
        bool fromNone = false;

        if (_saveName == "None")
        {
            _saveName = "Default";
            fromNone  = true;
        }
        if (!string.IsNullOrEmpty(saveName))
        {
            _saveName = saveName;
        }
#if UNITY_EDITOR
        if (fromNone)
        {
            NewGame();
        }
#endif
        JSONLevelSerializer.Deserialize(save);
#if UNITY_EDITOR
        lastSave = save;
#endif


        instance.Refresh();
    }
Esempio n. 3
0
    void OnGUI()
    {
        var tc = new TestClass {
            variable = 1, property = 2
        };

        tc.ints.Add(1);
        tc.ints.Add(2);
        tc.dic["hello"] = 1;
        tc.dic["mum"]   = 2;
        tc.intar[0]     = 99;
        tc.ar[0]        = tc.ints;
        tc.ar[1]        = tc.dic;
        tc.md[1, 1]     = 1000;


        if (GUILayout.Button("Press me"))
        {
            JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testIt.json", "testserializer", "T3sts3rializer", (error) => {
                Debug.Log(transform.position.ToString());
            });
        }
        if (GUILayout.Button("Or me"))
        {
            LevelSerializer.LoadSavedLevelFromFile("test.data");
        }
    }
Esempio n. 4
0
    public static void LoadSavedLevelFromFile(string filename)
    {
        StreamReader streamReader = File.OpenText(Application.persistentDataPath + "/" + filename);
        string       data         = streamReader.ReadToEnd();

        streamReader.Close();
        JSONLevelSerializer.LoadSavedLevel(data);
    }
Esempio n. 5
0
    public static void LoadObjectTreeFromFile(string filename, Action <JSONLevelLoader> onComplete = null)
    {
        StreamReader streamReader = File.OpenText(Application.persistentDataPath + "/" + filename);
        string       data         = streamReader.ReadToEnd();

        streamReader.Close();
        JSONLevelSerializer.LoadObjectTree(data, onComplete);
    }
Esempio n. 6
0
        public void Delete()
        {
            KeyValuePair <string, List <JSONLevelSerializer.SaveEntry> > keyValuePair = JSONLevelSerializer.SavedGames.FirstOrDefault((KeyValuePair <string, List <JSONLevelSerializer.SaveEntry> > p) => p.Value.Contains(this));

            if (keyValuePair.Value != null)
            {
                keyValuePair.Value.Remove(this);
                JSONLevelSerializer.SaveDataToPlayerPrefs();
            }
        }
Esempio n. 7
0
 private void OnMouseDown()
 {
     JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/SavedData" + this.id.ToString() + ".json", base.gameObject, "testserializer", "T3sts3rializer", delegate(Exception error)
     {
         Debug.Log("Uploaded!" + error);
     });
     UnityEngine.Object.Destroy(base.gameObject);
     Loom.QueueOnMainThread(delegate
     {
         Debug.Log("Downloading");
         JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/SavedData" + this.id.ToString() + ".json", null, null);
     }, 6f);
 }
Esempio n. 8
0
    // Use this for initialization
    void OnMouseDown()
    {
//		var data = JSONLevelSerializer.SaveObjectTree(gameObject);
        JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/SavedData" + id.ToString() + ".json", gameObject, "testserializer", "T3sts3rializer", (error) => {
            Debug.Log("Uploaded!" + error);
        });
        //data.WriteToFile("test_json.txt");
        Destroy(gameObject);
        Loom.QueueOnMainThread(() => {
            Debug.Log("Downloading");
            JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/SavedData" + id.ToString() + ".json", null, null);
        }, 6f);
    }
Esempio n. 9
0
 private void OnGUI()
 {
     using (new VerticalCentered())
     {
         if (this.targetGameObject && GUILayout.Button("Save to server JSON", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testme.json", this.targetGameObject, "testserializer", "T3sts3rializer", new Action <Exception>(this.Completed));
             UnityEngine.Object.Destroy(this.targetGameObject);
         }
         if (!this.targetGameObject && GUILayout.Button("Load from server JSON", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testme.json", new Action <JSONLevelLoader>(this.CompletedJSONLoad), null);
         }
         if (this.targetGameObject && GUILayout.Button("Save to server Binary", new GUILayoutOption[0]))
         {
             LevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testme.dat", this.targetGameObject, "testserializer", "T3sts3rializer", new Action <Exception>(this.Completed));
             UnityEngine.Object.Destroy(this.targetGameObject);
         }
         if (!this.targetGameObject && GUILayout.Button("Load from server Binary", new GUILayoutOption[0]))
         {
             LevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testme.dat", new Action <LevelLoader>(this.CompletedLoad));
         }
         if (GUILayout.Button("Save scene to server JSON", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testscene.json", "testserializer", "T3sts3rializer", new Action <Exception>(this.Completed));
         }
         if (GUILayout.Button("Load scene from server JSON", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.LoadSavedLevelFromServer("http://whydoidoit.net/testserializer/testscene.json", null);
         }
         if (GUILayout.Button("Save scene to server Binary", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testscene.data", "testserializer", "T3sts3rializer", new Action <Exception>(this.Completed));
         }
         if (GUILayout.Button("Load scene from server Binary", new GUILayoutOption[0]))
         {
             JSONLevelSerializer.LoadSavedLevelFromServer("http://whydoidoit.net/testserializer/testscene.data", null);
         }
     }
 }
Esempio n. 10
0
 void OnGUI()
 {
     using (new VerticalCentered())
     {
         if (targetGameObject && GUILayout.Button("Save to server JSON"))
         {
             JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testme.json", targetGameObject, "testserializer", "T3sts3rializer", Completed);
             Destroy(targetGameObject);
         }
         if (!targetGameObject && GUILayout.Button("Load from server JSON"))
         {
             JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testme.json", CompletedJSONLoad, null);
         }
         if (targetGameObject && GUILayout.Button("Save to server Binary"))
         {
             LevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testme.dat", targetGameObject, "testserializer", "T3sts3rializer", Completed);
             Destroy(targetGameObject);
         }
         if (!targetGameObject && GUILayout.Button("Load from server Binary"))
         {
             LevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testme.dat", CompletedLoad);
         }
         if (GUILayout.Button("Save scene to server JSON"))
         {
             JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testscene.json", "testserializer", "T3sts3rializer", Completed);
         }
         if (GUILayout.Button("Load scene from server JSON"))
         {
             JSONLevelSerializer.LoadSavedLevelFromServer("http://whydoidoit.net/testserializer/testscene.json", null);
         }
         if (GUILayout.Button("Save scene to server Binary"))
         {
             JSONLevelSerializer.SerializeLevelToServer("ftp://whydoidoit.net/testscene.data", "testserializer", "T3sts3rializer", Completed);
         }
         if (GUILayout.Button("Load scene from server Binary"))
         {
             JSONLevelSerializer.LoadSavedLevelFromServer("http://whydoidoit.net/testserializer/testscene.data", null);
         }
     }
 }
Esempio n. 11
0
    /// <summary>
    /// Load a game
    /// </summary>
    /// <param name="saveName"> The name of the "file" you want to load, will load the default or currently loaded "file" if left blank</param>
    public static void Load(string saveName = "")
    {
        bool fromNone = false;

        if (_saveName == "None")
        {
            _saveName = "Default";
            fromNone  = true;
        }
        if (!string.IsNullOrEmpty(saveName))
        {
            _saveName = saveName;
        }

        if (UnityEngine.PlayerPrefs.HasKey(_saveName))
        {
#if UNITY_EDITOR
            if (fromNone)
            {
                NewGame();
            }
#endif
            string save = UnityEngine.PlayerPrefs.GetString(_saveName);
            JSONLevelSerializer.Deserialize(save);
#if UNITY_EDITOR
            lastSave = save;
            if (lastSave == "")
            {
                //Prevents "value not used" prompt. The value lastSave is used in the Editor Script.
            }
#endif
        }
        else
        {
            NewGame();
        }

        instance.Refresh();
    }
Esempio n. 12
0
    private void Update()
    {
        RaycastHit raycastHit;

        if (Input.GetMouseButtonDown(0) && base.GetComponent <Collider>().Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out raycastHit, 1000f))
        {
            JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testspider" + this.id.ToString() + ".json", base.gameObject, "testserializer", "T3sts3rializer", delegate(Exception e)
            {
                if (e == null)
                {
                    Loom.QueueOnMainThread(delegate
                    {
                        JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testspider" + this.id, null, null);
                    }, 2f);
                }
                else
                {
                    Debug.Log(e.ToString());
                }
            });
            UnityEngine.Object.Destroy(base.gameObject);
        }
    }
Esempio n. 13
0
 // Update is called once per frame
 void Update()
 {
     if (Input.GetMouseButtonDown(0))
     {
         RaycastHit hit;
         if (GetComponent <Collider>().Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 1000))
         {
             JSONLevelSerializer.SaveObjectTreeToServer("ftp://whydoidoit.net/testspider" + id.ToString() + ".json", gameObject, "testserializer", "T3sts3rializer", (e) => {
                 if (e == null)
                 {
                     Loom.QueueOnMainThread(() => {
                         JSONLevelSerializer.LoadObjectTreeFromServer("http://whydoidoit.net/testserializer/testspider" + id);
                     }, 2f);
                 }
                 else
                 {
                     Debug.Log(e.ToString());
                 }
             });
             Destroy(gameObject);
         }
     }
 }
Esempio n. 14
0
    public IEnumerator Load(int numberOfFrames, float timeScale = 0)
    {
        loadingCount++;
        var oldFixedTime = Time.fixedDeltaTime;

        Time.fixedDeltaTime = 9;
        //Need to wait while the base level is prepared, it takes 2 frames
        while (numberOfFrames-- > 0)
        {
            yield return(new WaitForEndOfFrame());
        }
        if (LevelSerializer.ShouldCollect && timeScale == 0)
        {
            GC.Collect();
        }

        LevelSerializer.RaiseProgress("Initializing", 0);
        if (Data.rootObject != null)
        {
            Debug.Log(Data.StoredObjectNames.Any(sn => sn.Name == Data.rootObject) ? "Located " + Data.rootObject : "Not found " + Data.rootObject);
        }
        //Check if we should be deleting missing items
        if (!DontDelete)
        {
            //First step is to remove any items that should not exist according to the saved scene
            foreach (var go in
                     UniqueIdentifier.AllIdentifiers.Where(n => Data.StoredObjectNames.All(sn => sn.Name != n.Id)).ToList())
            {
                try
                {
                    var cancel = false;
                    OnDestroyObject(go.gameObject, ref cancel);
                    if (!cancel)
                    {
                        Destroy(go.gameObject);
                    }
                }
                catch (Exception e)
                {
                    Radical.LogWarning("Problem destroying object " + go.name + " " + e.ToString());
                }
            }
        }

        var flaggedObjects = new List <UniqueIdentifier>();

        LevelSerializer.RaiseProgress("Initializing", 0.25f);

        var position = new Vector3(0, 2000, 2000);

        //Next we need to instantiate any items that are needed by the stored scene
        foreach (var sto in
                 Data.StoredObjectNames.Where(c => UniqueIdentifier.GetByName(c.Name) == null))
        {
            try
            {
                if (sto.createEmptyObject || sto.ClassId == null || !LevelSerializer.AllPrefabs.ContainsKey(sto.ClassId))
                {
                    sto.GameObject = new GameObject("CreatedObject");
                    sto.GameObject.transform.position = position;
                    var emptyObjectMarker = sto.GameObject.AddComponent <EmptyObjectIdentifier>();
                    sto.GameObject.AddComponent <StoreMaterials>();
                    sto.GameObject.AddComponent <StoreMesh>();
                    emptyObjectMarker.IsDeserializing = true;
                    emptyObjectMarker.Id = sto.Name;
                    if (emptyObjectMarker.Id == Data.rootObject)
                    {
                        Debug.Log("Set the root object on an empty");
                    }
                    flaggedObjects.Add(emptyObjectMarker);
                }
                else
                {
                    var pf     = LevelSerializer.AllPrefabs[sto.ClassId];
                    var cancel = false;
                    CreateGameObject(pf, ref cancel);
                    if (cancel)
                    {
                        Debug.LogWarning("Cancelled");
                        continue;
                    }
                    var uis = pf.GetComponentsInChildren <UniqueIdentifier>();
                    foreach (var ui in uis)
                    {
                        ui.IsDeserializing = true;
                    }
                    sto.GameObject = Instantiate(pf, position, Quaternion.identity) as GameObject;
                    sto.GameObject.GetComponent <UniqueIdentifier>().Id = sto.Name;
                    if (sto.GameObject.GetComponent <UniqueIdentifier>().Id == Data.rootObject)
                    {
                        Debug.Log("Set the root object on a prefab");
                    }
                    foreach (var ui in uis)
                    {
                        ui.IsDeserializing = false;
                    }
                    flaggedObjects.AddRange(sto.GameObject.GetComponentsInChildren <UniqueIdentifier>());
                }

                position += Vector3.right * 50;
                sto.GameObject.GetComponent <UniqueIdentifier>().Id = sto.Name;
                sto.GameObject.name = sto.GameObjectName;
                if (sto.ChildIds.Count > 0)
                {
                    var list = sto.GameObject.GetComponentsInChildren <UniqueIdentifier>().ToList();
                    for (var i = 0; i < list.Count && i < sto.ChildIds.Count; i++)
                    {
                        list[i].Id = sto.ChildIds[i];
                    }
                }
                if (sto.Children.Count > 0)
                {
                    var list = JSONLevelSerializer.GetComponentsInChildrenWithClause(sto.GameObject);
                    _indexDictionary.Clear();
                    foreach (var c in list)
                    {
                        if (!sto.Children.ContainsKey(c.ClassId))
                        {
                            continue;
                        }
                        if (!_indexDictionary.ContainsKey(c.ClassId))
                        {
                            _indexDictionary[c.ClassId] = 0;
                        }
                        c.Id = sto.Children[c.ClassId][_indexDictionary[c.ClassId]];
                        _indexDictionary[c.ClassId] = _indexDictionary[c.ClassId] + 1;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                Radical.LogWarning("Problem creating an object " + sto.GameObjectName + " with classID " + sto.ClassId + " " + e);
            }
        }
        var loadedGameObjects = new HashSet <GameObject>();

        LevelSerializer.RaiseProgress("Initializing", 0.75f);


        foreach (var so in Data.StoredObjectNames)
        {
            var go = UniqueIdentifier.GetByName(so.Name);
            if (go == null)
            {
                Radical.LogNow("Could not find " + so.GameObjectName + " " + so.Name);
            }
            else
            {
                loadedGameObjects.Add(go);
                if (so.Components != null && so.Components.Count > 0)
                {
                    var all = go.GetComponents <Component>().Where(c => !typeof(UniqueIdentifier).IsAssignableFrom(c.GetType())).ToList();
                    foreach (var comp in all)
                    {
                        if (!so.Components.ContainsKey(comp.GetType().FullName))
                        {
                            Destroy(comp);
                        }
                    }
                }
                SetActive(go, so.Active);
                if (so.setExtraData)
                {
                    go.layer = so.layer;
                    go.tag   = so.tag;
                }
            }
        }

        LevelSerializer.RaiseProgress("Initializing", 0.85f);

        if (rootObject != null)
        {
            if (UniqueIdentifier.GetByName(Data.rootObject) == null)
            {
                Debug.Log("No root object has been configured");
            }
        }

        foreach (var go in Data.StoredObjectNames.Where(c => !string.IsNullOrEmpty(c.ParentName)))
        {
            var parent = UniqueIdentifier.GetByName(go.ParentName);
            var item   = UniqueIdentifier.GetByName(go.Name);
            if (item != null && parent != null)
            {
                item.transform.parent = parent.transform;
            }
        }


        //Newly created objects should have the time to start
        Time.timeScale = timeScale;
        //yield return new WaitForEndOfFrame();
        //yield return new WaitForEndOfFrame();


        LevelSerializer.RaiseProgress("Initializing", 1f);


        using (new Radical.Logging())
        {
            var currentProgress = 0;
            UnitySerializer.FinalProcess process;
            using (new UnitySerializer.ForceJSON())
            {
                using (new UnitySerializer.SerializationSplitScope())
                {
                    using (new UnitySerializer.SerializationScope())
                    {
                        //Now we restore the data for the items
                        foreach (var item in
                                 Data.StoredItems.GroupBy(i => i.Name,
                                                          (name, cps) => new
                        {
                            Name = name,
                            Components = cps.Where(cp => cp.Name == name).GroupBy(cp => cp.Type,
                                                                                  (type, components) => new
                            {
                                Type = type,
                                List = components.ToList()
                            }).ToList()
                        }))
                        {
                #if US_LOGGING
                            Radical.Log("\n*****************\n{0}\n********START**********\n", item.Name);
                            Radical.IndentLog();
                #endif
                            var go = UniqueIdentifier.GetByName(item.Name);
                            if (go == null)
                            {
                                Radical.LogWarning(item.Name + " was null");
                                continue;
                            }


                            foreach (var cp in item.Components)
                            {
                                try
                                {
                                    LevelSerializer.RaiseProgress("Loading", (float)++currentProgress / (float)Data.StoredItems.Count);
                                    var type = UnitySerializer.GetTypeEx(cp.Type);
                                    if (type == null)
                                    {
                                        continue;
                                    }
                                    Last = go;
                                    var cancel = false;
                                    LoadData(go, ref cancel);
                                    LoadComponent(go, type.Name, ref cancel);
                                    if (cancel)
                                    {
                                        continue;
                                    }

                #if US_LOGGING
                                    Radical.Log("<{0}>\n", type.FullName);
                                    Radical.IndentLog();
                #endif

                                    var list = go.GetComponents(type).Where(c => c.GetType() == type).ToList();
                                    //Make sure the lists are the same length
                                    while (list.Count > cp.List.Count)
                                    {
                                        DestroyImmediate(list.Last());
                                        list.Remove(list.Last());
                                    }
                                    if (type == typeof(NavMeshAgent))
                                    {
                                        var    cp1     = cp;
                                        var    item1   = item;
                                        Action perform = () =>
                                        {
                                            var comp  = cp1;
                                            var tp    = type;
                                            var tname = item1.Name;
                                            UnitySerializer.AddFinalAction(() =>
                                            {
                                                var g     = UniqueIdentifier.GetByName(tname);
                                                var nlist = g.GetComponents(tp).Where(c => c.GetType() == tp).ToList();
                                                while (nlist.Count < comp.List.Count)
                                                {
                                                    try
                                                    {
                                                        nlist.Add(g.AddComponent(tp));
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                                list = list.Where(l => l != null).ToList();
                                                //Now deserialize the items back in
                                                for (var i = 0; i < nlist.Count; i++)
                                                {
                                                    if (JSONLevelSerializer.CustomSerializers.ContainsKey(tp))
                                                    {
                                                        JSONLevelSerializer.CustomSerializers[tp].Deserialize(
                                                            UnitySerializer.TextEncoding.GetBytes(UnitySerializer.UnEscape(comp.List[i].Data)), nlist[i]);
                                                    }
                                                    else
                                                    {
                                                        UnitySerializer.JSONDeserializeInto(UnitySerializer.UnEscape(comp.List[i].Data), nlist[i]);
                                                    }
                                                    LoadedComponent(nlist[i]);
                                                }
                                            });
                                        };
                                        perform();
                                    }
                                    else
                                    {
                                        while (list.Count < cp.List.Count)
                                        {
                                            try
                                            {
                #if US_LOGGING
                                                Radical.Log("Adding component of type " + type.ToString());
                #endif
                                                list.Add(go.AddComponent(type));
                                            }
                                            catch
                                            {
                                            }
                                        }
                                        list = list.Where(l => l != null).ToList();
                                        //Now deserialize the items back in
                                        for (var i = 0; i < list.Count; i++)
                                        {
                                            Radical.Log(string.Format("Deserializing {0} for {1}", type.Name, go.GetFullName()));
                                            if (JSONLevelSerializer.CustomSerializers.ContainsKey(type))
                                            {
                                                JSONLevelSerializer.CustomSerializers[type].Deserialize(UnitySerializer.TextEncoding.GetBytes(cp.List[i].Data), list[i]);
                                            }
                                            else
                                            {
                                                UnitySerializer.JSONDeserializeInto(cp.List[i].Data, list[i]);
                                            }
                                            LoadedComponent(list[i]);
                                        }
                                    }
                #if US_LOGGING
                                    Radical.OutdentLog();
                                    Radical.Log("</{0}>", type.FullName);
                #endif
                                }
                                catch (Exception e)
                                {
                                    Radical.LogWarning("Problem deserializing " + cp.Type + " for " + go.name + " " + e.ToString());
                                }
                            }

                #if US_LOGGING
                            Radical.OutdentLog();
                            Radical.Log("\n*****************\n{0}\n********END**********\n\n", item.Name);
                #endif
                        }

                        process = UnitySerializer.TakeOwnershipOfFinalization();
                    }
                }
            }

            UnitySerializer.RunDeferredActions(process, 2, false);

            Time.fixedDeltaTime = oldFixedTime;
            Time.timeScale      = 1;
            yield return(new WaitForFixedUpdate());

            Time.timeScale = timeScaleAfterLoading;

            UnitySerializer.RunDeferredActions(process);

            //Finally we need to fixup any references to other game objects,
            //these have been stored in a list inside the serializer
            //waiting for us to call this.  Vector3s are also deferred until this point
            //UnitySerializer.RunDeferredActions(2);
            if (LevelSerializer.ShouldCollect && timeScale == 0)
            {
                Resources.UnloadUnusedAssets();
                GC.Collect();
            }

            UnitySerializer.InformDeserializedObjects(process);


            //Tell the world that the level has been loaded
            //LevelSerializer.InvokeDeserialized();
            if (Data.rootObject != null)
            {
                rootObject = UniqueIdentifier.GetByName(Data.rootObject);
            }
            else
            {
                rootObject = null;
            }

            if (rootObject == null && Data.rootObject != null)
            {
                Debug.LogError("Could not find the root object");
                Debug.Log(Data.rootObject + " not found " + (!Data.StoredObjectNames.Any(n => n.Name == Data.rootObject) ? "not in the stored names" : "was in the stored names"));
            }

            //Flag that we aren't deserializing
            foreach (var obj in flaggedObjects)
            {
                obj.IsDeserializing = false;
                obj.SendMessage("OnDeserialized", SendMessageOptions.DontRequireReceiver);
            }


            loading = false;
            LevelSerializer.IsDeserializing = false;
            RoomManager.loadingRoom         = false;
            //Restore the time scale
            whenCompleted(rootObject, loadedGameObjects.ToList());
            //Get rid of the current object that is holding this level loader, it was
            //created solely for the purpose of running this script
            Destroy(gameObject, 0.1f);
        }
    }
Esempio n. 15
0
    void OnGUI()
    {
        if (_assetStore.Count == 0)
        {
            BuildLocalAssetStore();
        }
        var bold     = new GUIStyle("label");
        var boldFold = new GUIStyle("foldout");

        bold.fontStyle     = FontStyle.Bold;
        bold.fontSize      = 14;
        boldFold.fontStyle = FontStyle.Bold;
        var someMatched = false;

        using (new Horizontal()) {
            if (GUILayout.Toggle(showMain, "Save Game", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = true;
                showReferences = false;
                showRoom       = false;
            }

            if (GUILayout.Toggle(showRoom, "Rooms", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = false;
                showRoom       = true;
                showReferences = false;
            }
            if (_assetStore.SelectMany(s => s.Value).All(s => s.Value.Count <= 1))
            {
                GUI.color = Color.white;
            }
            else
            {
                someMatched = true;
                GUI.color   = Color.yellow;
            }

            if (GUILayout.Toggle(showReferences, "References", "toolbarbutton", GUILayout.ExpandWidth(false)))
            {
                showMain       = false;
                showRoom       = false;
                showReferences = true;
            }
            GUILayout.Label("", "toolbarbutton");
            GUI.color = Color.white;
        }
        if (showReferences)
        {
            using (new ScrollView(ref scroll)) {
                using (new Vertical()) {
                    foreach (var tp in _assetStore)
                    {
                        if (!open.ContainsKey(tp.Key))
                        {
                            open [tp.Key] = false;
                        }

                        if (tp.Value.Any(v => v.Value.Count > 1))
                        {
                            GUI.color     = Color.yellow;
                            open [tp.Key] = EditorGUILayout.Foldout(open [tp.Key], tp.Key.ToString(), boldFold);
                            GUI.color     = Color.white;
                        }
                        else
                        {
                            open [tp.Key] = EditorGUILayout.Foldout(open [tp.Key], tp.Key.ToString(), "foldout");
                        }
                        if (open [tp.Key])
                        {
                            foreach (var n in tp.Value.OrderByDescending(q => q.Value.Count).ThenBy(q => q.Key))
                            {
                                using (new Horizontal()) {
                                    GUILayout.Space(10);
                                    if (!open.ContainsKey(tp.Key + n.Key))
                                    {
                                        open [tp.Key + n.Key] = false;
                                    }
                                    if (n.Value.Count <= 1)
                                    {
                                        open[tp.Key + n.Key] = false;
                                        if (GUILayout.Button(n.Key, "label"))
                                        {
                                            Selection.activeObject = n.Value[0] as UnityEngine.Object;
                                            EditorGUIUtility.PingObject(n.Value[0] as UnityEngine.Object);
                                        }
                                    }
                                    else
                                    {
                                        open [tp.Key + n.Key] = EditorGUILayout.Foldout(open [tp.Key + n.Key], n.Key + " (" + n.Value.Count + ")", boldFold);
                                    }
                                }
                                if (open [tp.Key + n.Key])
                                {
                                    using (new Vertical()) {
                                        foreach (var i in n.Value.Cast <UnityEngine.Object>())
                                        {
                                            using (new Horizontal()) {
                                                GUILayout.Space(20);
                                                var addOn = "";
                                                if (!AssetDatabase.IsMainAsset(i) && !AssetDatabase.IsSubAsset(i))
                                                {
                                                    GUI.color = Color.red;
                                                    addOn     = " (internal to Unity)";
                                                }
                                                else
                                                {
                                                    GUI.color = Color.white;
                                                }
                                                if (GUILayout.Button(i.name.ToString() + addOn, "label"))
                                                {
                                                    Selection.activeObject = i as UnityEngine.Object;
                                                    EditorGUIUtility.PingObject(i);
                                                }
                                                GUI.color = Color.white;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (someMatched)
            {
                var style = new GUIStyle("label");
                style.wordWrap = true;

                GUILayout.Space(5);
                GUI.color = Color.yellow;
                GUILayout.Label("Warning", bold);
                GUI.color = Color.white;
                GUILayout.Label("Some referencable items have the same name. This is only a problem if you actually refer to one of the items in a saved variable and then more get added with the same name (existing saved games may load the wrong instance), or if for some other reason Unity reorders the similarly named items.  If you use a highlighted item as a reference it may be worth renaming it to be a unique name if you can.", style);
                GUILayout.Space(5);
            }
        }

        if (showMain)
        {
            GUILayout.BeginVertical();
            if (Selection.gameObjects.Length == 1)
            {
                if (Selection.activeGameObject != null)
                {
                    GUILayout.Space(8);
                    using (new HorizontalCentered()) {
                        GUILayout.Label(Selection.activeGameObject.name, bold);
                    }
                    using (new HorizontalCentered()) {
                        GUI.color = new Color(0.8f, 1f, 0.8f, 1);

                        if (Has(Selection.activeGameObject, typeof(UniqueIdentifier)))
                        {
                            GUILayout.Label("Uniquely Identified");
                        }
                        else if (Has(Selection.activeGameObject, typeof(StoreInformation)))
                        {
                            GUILayout.Label("Storing Information");
                        }
                        else if (Has(Selection.activeGameObject, typeof(PrefabIdentifier)))
                        {
                            GUILayout.Label("Prefab Identifier");
                        }
                        else
                        {
                            GUI.color = Color.gray;
                            GUILayout.Label("Nothing stored");
                        }
                        if (Has(Selection.activeGameObject, typeof(StoreMaterials)))
                        {
                            GUILayout.Label(" + materials");
                        }
                        if (Has(Selection.activeGameObject, typeof(StoreMesh)))
                        {
                            GUILayout.Label(" + mesh");
                        }
                    }
                    GUILayout.Space(4);
                    GUI.color = Color.white;
                    using (new HorizontalCentered()) {
                        using (new Vertical()) {
                            using (new Horizontal()) {
                                if (!Has(Selection.activeGameObject, typeof(UniqueIdentifier)) && GUILayout.Button("Unique Identifier"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    Add(typeof(UniqueIdentifier), Selection.activeGameObject);
                                }
                                if (!Has(Selection.activeGameObject, typeof(StoreInformation)) && GUILayout.Button("Store Information"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    Add(typeof(StoreInformation), Selection.activeGameObject);
                                }
                                if (Selection.activeGameObject.GetComponent <StoreMaterials>() == null && Selection.activeGameObject.GetComponent <StoreInformation>() != null)
                                {
                                    if (GUILayout.Button("Store Materials"))
                                    {
                                        Undo.RegisterSceneUndo("Change Identifiers");
                                        Selection.activeGameObject.AddComponent <StoreMaterials>();
                                    }
                                }
                                if (Selection.activeGameObject.GetComponent <StoreMesh>() == null && Selection.activeGameObject.GetComponent <StoreInformation>() != null && (Selection.activeGameObject.GetComponent <MeshFilter>() != null || Selection.activeGameObject.GetComponent <SkinnedMeshRenderer>() != null))
                                {
                                    if (GUILayout.Button("Store Mesh"))
                                    {
                                        Undo.RegisterSceneUndo("Change Identifiers");
                                        Selection.activeGameObject.AddComponent <StoreMesh>();
                                    }
                                }
                            }
                            using (new Horizontal()) {
                                if (!Has(Selection.activeGameObject, typeof(PrefabIdentifier)) && PrefabUtility.GetPrefabType(Selection.activeGameObject) != PrefabType.None && GUILayout.Button("Prefab Identifier"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    Add(typeof(PrefabIdentifier), Selection.activeGameObject);
                                    PrefabUtility.ReplacePrefab(Selection.activeGameObject, PrefabUtility.GetPrefabParent(Selection.activeGameObject), ReplacePrefabOptions.ConnectToPrefab);
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    foreach (var c in Selection.activeGameObject.GetComponents <UniqueIdentifier>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreMaterials>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreMesh>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                    GUILayout.Space(12);
                    if (Selection.activeGameObject.transform.Cast <Transform> ().Count() > 0)
                    {
                        using (new HorizontalCentered()) {
                            GUILayout.Label(Selection.activeGameObject.name, bold);
                            bold.fontStyle = FontStyle.Italic;
                            GUILayout.Label("+ Children", bold);
                        }
                        GUILayout.Space(6);
                        using (new HorizontalCentered()) {
                            using (new Vertical()) {
                                using (new Horizontal()) {
                                    if (GUILayout.Button("Unique Identifier"))
                                    {
                                        Undo.RegisterSceneUndo("Change Identifiers");
                                        foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !Has(g, typeof(UniqueIdentifier))))
                                        {
                                            Add(typeof(UniqueIdentifier), c);
                                        }
                                    }
                                    if (GUILayout.Button("Store Information"))
                                    {
                                        Undo.RegisterSceneUndo("Change Identifiers");
                                        foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !Has(g, typeof(StoreInformation))))
                                        {
                                            Add(typeof(StoreInformation), c);
                                        }
                                    }
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove All"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <UniqueIdentifier>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <StoreMaterials>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                    foreach (var c in Selection.activeGameObject.GetComponents <StoreMesh>())
                                    {
                                        DestroyImmediate(c, true);
                                    }
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                }
            }
            else if (Selection.gameObjects.Length > 0)
            {
                using (new HorizontalCentered()) {
                    GUILayout.Label("Selected Objects", bold);
                }
                GUILayout.Space(6);
                using (new HorizontalCentered()) {
                    using (new Vertical()) {
                        using (new Horizontal()) {
                            if (GUILayout.Button("Unique Identifier"))
                            {
                                Undo.RegisterSceneUndo("Change Identifiers");
                                foreach (var c in Selection.gameObjects)
                                {
                                    Add(typeof(UniqueIdentifier), c);
                                }
                            }
                            if (GUILayout.Button("Store Information"))
                            {
                                Undo.RegisterSceneUndo("Change Identifiers");
                                foreach (var c in Selection.gameObjects)
                                {
                                    Add(typeof(StoreInformation), c);
                                }
                            }
                        }
                        using (new Horizontal())
                        {
                            if (GUILayout.Button("Store Materials"))
                            {
                                foreach (var c in Selection.gameObjects.Where(g => g.GetComponent <StoreMaterials>() == null && g.GetComponent <Renderer>() != null))
                                {
                                    c.AddComponent <StoreMaterials>();
                                }
                            }
                            GUI.color = new Color(0.9f, 0.5f, 0.5f);
                            if (GUILayout.Button("Remove All"))
                            {
                                Undo.RegisterSceneUndo("Change Identifiers");
                                foreach (var c in Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <UniqueIdentifier>()))
                                {
                                    DestroyImmediate(c);
                                }
                            }
                            GUI.color = Color.white;
                        }
                    }
                }
            }
            GUILayout.FlexibleSpace();
            var items = GameObject.FindObjectsOfType(typeof(SaveGameManager));
            if (items == null || items.Length == 0)
            {
                GUI.color = new Color(1, 0.6f, 0.6f, 1f);
                var style = new GUIStyle("label");
                style.wordWrap = true;
                GUILayout.Label("You need to assign a Save Game Manager script to an object in this scene.  This object should be something that ISN'T loaded and saved with one of the scripts, and NOT set to DontDestroyOnLoad.", style);
                GUILayout.Space(6);
                GUI.color = Color.white;
                using (new Horizontal()) {
                    if (Selection.activeGameObject != null && GUILayout.Button("Assign Save Game Manager"))
                    {
                        Undo.RegisterSceneUndo("Assign save game manager");
                        Selection.activeGameObject.AddComponent <SaveGameManager> ();
                    }
                    if (GUILayout.Button("Create a new Save Game Manager"))
                    {
                        Undo.RegisterSceneUndo("Create save game manager");
                        var go = new GameObject();
                        go.name = "Save Game Manager";
                        go.AddComponent <SaveGameManager> ();
                    }
                }
                GUILayout.Space(15);
            }



            GUILayout.Label("Maintenance");
            using (new Horizontal()) {
                if (GUILayout.Button("Delete all saved games"))
                {
                    if (EditorUtility.DisplayDialog("Delete Saved Games",
                                                    "Are you sure you want to delete all of the saved games?", "Yes", "No"))
                    {
                        LevelSerializer.SavedGames.Clear();
                        LevelSerializer.SaveDataToPlayerPrefs();
                        JSONLevelSerializer.SavedGames.Clear();
                        JSONLevelSerializer.SaveDataToPlayerPrefs();
                    }
                }
                if (GameObject.FindObjectsOfType(typeof(SaveGameManager)).Length != 0 && GUILayout.Button("Capture All Objects"))
                {
                    EditorApplication.isPlaying = true;
                    stopWhenReady = 50;
                }
            }
            GUILayout.Space(8);
            using (new Horizontal()) {
                GUILayout.Label(string.Format("Tracked Scene Items: {0:#,0}", UniqueIdentifier.AllIdentifiers.Count));
                var old = drawInfo;
                drawInfo = GUILayout.Toggle(drawInfo, "Hierarchy markers");
                if (old != drawInfo)
                {
                    EditorApplication.RepaintHierarchyWindow();
                    EditorPrefs.SetBool("UnitySerializer.drawHierarchy", drawInfo);
                }
            }
            GUILayout.Space(4);
            GUILayout.EndVertical();
        }

        if (showRoom)
        {
            if (GameObject.FindObjectsOfType(typeof(Room)).Length > 0)
            {
                GUILayout.BeginVertical();
                if (Selection.gameObjects.Length == 1)
                {
                    if (Selection.activeGameObject != null)
                    {
                        GUILayout.Space(8);
                        using (new HorizontalCentered()) {
                            GUILayout.Label(Selection.activeGameObject.name, bold);
                        }
                        using (new HorizontalCentered()) {
                            GUI.color = new Color(0.8f, 1f, 0.8f, 1);


                            if (Selection.activeGameObject.GetComponent <DontStoreObjectInRoom>())
                            {
                                GUILayout.Label(Has(Selection.activeGameObject, typeof(StoreInformation)) ?  "Stored in the save game but not stored in the room state" : "Not saved but flagged for exclusion anyway.");
                            }
                            else if (Has(Selection.activeGameObject, typeof(StoreInformation)))
                            {
                                GUILayout.Label("Stored in the saved game and the room");
                            }
                        }
                        GUILayout.Space(4);
                        GUI.color = Color.white;
                        using (new HorizontalCentered()) {
                            using (new Vertical()) {
                                using (new Horizontal()) {
                                    if (!Selection.activeGameObject.GetComponent <DontStoreObjectInRoom>() && GUILayout.Button("Exclude from room"))
                                    {
                                        Undo.RegisterSceneUndo("Exclude");
                                        Add(typeof(DontStoreObjectInRoom), Selection.activeGameObject);
                                    }
                                }
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    foreach (var c in Selection.activeGameObject.GetComponents <DontStoreObjectInRoom>())
                                    {
                                        DestroyImmediate(c);
                                    }
                                }
                                GUI.color = Color.white;
                            }
                        }
                        GUILayout.Space(12);
                        if (Selection.activeGameObject.transform.Cast <Transform> ().Count() > 0)
                        {
                            using (new HorizontalCentered()) {
                                GUILayout.Label(Selection.activeGameObject.name, bold);
                                bold.fontStyle = FontStyle.Italic;
                                GUILayout.Label("+ Children", bold);
                            }
                            GUILayout.Space(6);
                            using (new HorizontalCentered()) {
                                using (new Vertical()) {
                                    using (new Horizontal()) {
                                        if (GUILayout.Button("Exclude from room"))
                                        {
                                            Undo.RegisterSceneUndo("Change Identifiers");
                                            foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <Transform>().Select(t => t.gameObject).Where(g => !g.GetComponent <DontStoreObjectInRoom>()))
                                            {
                                                Add(typeof(DontStoreObjectInRoom), c);
                                            }
                                        }


                                        GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                        if (GUILayout.Button("Remove"))
                                        {
                                            Undo.RegisterSceneUndo("Change Identifiers");
                                            foreach (var c in Selection.activeGameObject.GetAllComponentsInChildren <DontStoreObjectInRoom>())
                                            {
                                                DestroyImmediate(c);
                                            }
                                        }
                                        GUI.color = Color.white;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (Selection.gameObjects.Length > 0)
                {
                    using (new HorizontalCentered()) {
                        GUILayout.Label("Selected Objects", bold);
                    }
                    GUILayout.Space(6);
                    using (new HorizontalCentered()) {
                        using (new Vertical()) {
                            using (new Horizontal()) {
                                if (GUILayout.Button("Exlude from room"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    foreach (var c in Selection.gameObjects.Where(g => g.GetComponent <DontStoreObjectInRoom>()))
                                    {
                                        Add(typeof(DontStoreObjectInRoom), c);
                                    }
                                }
                            }
                            using (new Horizontal())
                            {
                                GUI.color = new Color(0.9f, 0.5f, 0.5f);
                                if (GUILayout.Button("Remove"))
                                {
                                    Undo.RegisterSceneUndo("Change Identifiers");
                                    foreach (var c in Selection.gameObjects.Cast <GameObject>().SelectMany(s => s.GetAllComponentsInChildren <DontStoreObjectInRoom>()))
                                    {
                                        DestroyImmediate(c);
                                    }
                                }
                                GUI.color = Color.white;
                            }
                        }
                    }
                }
            }
            GUILayout.FlexibleSpace();
            if (GameObject.FindObjectsOfType(typeof(Room)).Length == 0)
            {
                GUI.color = new Color(1, 0.6f, 0.6f, 1f);
                var style = new GUIStyle("label");
                style.wordWrap = true;
                GUILayout.Label("You need to assign a Room Manager script to an object in this scene.  This object should be something that IS loaded and saved with one of the scripts, and NOT set to DontDestroyOnLoad.", style);
                GUILayout.Space(6);
                GUI.color = Color.white;
                using (new Horizontal()) {
                    if (GUILayout.Button("Create a new Room Manager"))
                    {
                        Undo.RegisterSceneUndo("Create room manager");
                        var go = new GameObject();
                        go.name = "Room Manager";
                        go.AddComponent <StoreInformation> ();
                        go.AddComponent <RoomDataSaveGameStorage>();
                        go.AddComponent <Room>();
                    }
                }
                GUILayout.Space(15);
            }



            GUILayout.Label("Maintenance");
            using (new Horizontal()) {
                if (GUILayout.Button("Delete all saved games"))
                {
                    if (EditorUtility.DisplayDialog("Delete Saved Games",
                                                    "Are you sure you want to delete all of the saved games?", "Yes", "No"))
                    {
                        LevelSerializer.SavedGames.Clear();
                        LevelSerializer.SaveDataToPlayerPrefs();
                        JSONLevelSerializer.SavedGames.Clear();
                        JSONLevelSerializer.SaveDataToPlayerPrefs();
                    }
                }
                if (GameObject.FindObjectsOfType(typeof(SaveGameManager)).Length != 0 && GUILayout.Button("Capture All Objects"))
                {
                    EditorApplication.isPlaying = true;
                    stopWhenReady = 50;
                }
            }
            GUILayout.Space(8);
            using (new Horizontal()) {
                GUILayout.Label(string.Format("Tracked Scene Items: {0:#,0}", UniqueIdentifier.AllIdentifiers.Count));
                var old = drawInfo;
                drawInfo = GUILayout.Toggle(drawInfo, "Hierarchy markers");
                if (old != drawInfo)
                {
                    EditorApplication.RepaintHierarchyWindow();
                    EditorPrefs.SetBool("UnitySerializer.drawHierarchy", drawInfo);
                }
            }
            GUILayout.Space(4);
            GUILayout.EndVertical();
        }
        Repaint();
    }
Esempio n. 16
0
    public IEnumerator Load(int numberOfFrames, float timeScale = 0f)
    {
        JSONLevelLoader.loadingCount++;
        float oldFixedTime = Time.fixedDeltaTime;

        Time.fixedDeltaTime = 9f;
        for (;;)
        {
            int num;
            numberOfFrames = (num = numberOfFrames) - 1;
            if (num <= 0)
            {
                break;
            }
            yield return(new WaitForEndOfFrame());
        }
        if (LevelSerializer.ShouldCollect && timeScale == 0f)
        {
            GC.Collect();
        }
        LevelSerializer.RaiseProgress("Initializing", 0f);
        if (this.Data.rootObject != null)
        {
            Debug.Log((!this.Data.StoredObjectNames.Any((JSONLevelSerializer.StoredItem sn) => sn.Name == this.$this.Data.rootObject)) ? ("Not found " + this.Data.rootObject) : ("Located " + this.Data.rootObject));
        }
        if (!this.DontDelete)
        {
            foreach (UniqueIdentifier uniqueIdentifier in UniqueIdentifier.AllIdentifiers.Where(delegate(UniqueIdentifier n)
            {
                JSONLevelLoader $this = this.$this;
                return(this.$this.Data.StoredObjectNames.All((JSONLevelSerializer.StoredItem sn) => sn.Name != n.Id));
            }).ToList <UniqueIdentifier>())
            {
                try
                {
                    bool flag = false;
                    JSONLevelLoader.OnDestroyObject(uniqueIdentifier.gameObject, ref flag);
                    if (!flag)
                    {
                        UnityEngine.Object.Destroy(uniqueIdentifier.gameObject);
                    }
                }
                catch (Exception ex)
                {
                    Radical.LogWarning("Problem destroying object " + uniqueIdentifier.name + " " + ex.ToString());
                }
            }
        }
        List <UniqueIdentifier> flaggedObjects = new List <UniqueIdentifier>();

        LevelSerializer.RaiseProgress("Initializing", 0.25f);
        Vector3 position = new Vector3(0f, 2000f, 2000f);

        foreach (JSONLevelSerializer.StoredItem storedItem in from c in this.Data.StoredObjectNames
                 where UniqueIdentifier.GetByName(c.Name) == null
                 select c)
        {
            try
            {
                if (storedItem.createEmptyObject || storedItem.ClassId == null || !LevelSerializer.AllPrefabs.ContainsKey(storedItem.ClassId))
                {
                    storedItem.GameObject = new GameObject("CreatedObject");
                    storedItem.GameObject.transform.position = position;
                    EmptyObjectIdentifier emptyObjectIdentifier = storedItem.GameObject.AddComponent <EmptyObjectIdentifier>();
                    storedItem.GameObject.AddComponent <StoreMaterials>();
                    storedItem.GameObject.AddComponent <StoreMesh>();
                    emptyObjectIdentifier.IsDeserializing = true;
                    emptyObjectIdentifier.Id = storedItem.Name;
                    if (emptyObjectIdentifier.Id == this.Data.rootObject)
                    {
                        Debug.Log("Set the root object on an empty");
                    }
                    flaggedObjects.Add(emptyObjectIdentifier);
                }
                else
                {
                    GameObject gameObject = LevelSerializer.AllPrefabs[storedItem.ClassId];
                    bool       flag2      = false;
                    JSONLevelLoader.CreateGameObject(gameObject, ref flag2);
                    if (flag2)
                    {
                        Debug.LogWarning("Cancelled");
                        continue;
                    }
                    UniqueIdentifier[] componentsInChildren = gameObject.GetComponentsInChildren <UniqueIdentifier>();
                    foreach (UniqueIdentifier uniqueIdentifier2 in componentsInChildren)
                    {
                        uniqueIdentifier2.IsDeserializing = true;
                    }
                    storedItem.GameObject = UnityEngine.Object.Instantiate <GameObject>(gameObject, position, Quaternion.identity);
                    storedItem.GameObject.GetComponent <UniqueIdentifier>().Id = storedItem.Name;
                    if (storedItem.GameObject.GetComponent <UniqueIdentifier>().Id == this.Data.rootObject)
                    {
                        Debug.Log("Set the root object on a prefab");
                    }
                    foreach (UniqueIdentifier uniqueIdentifier3 in componentsInChildren)
                    {
                        uniqueIdentifier3.IsDeserializing = false;
                    }
                    flaggedObjects.AddRange(storedItem.GameObject.GetComponentsInChildren <UniqueIdentifier>());
                }
                position += Vector3.right * 50f;
                storedItem.GameObject.GetComponent <UniqueIdentifier>().Id = storedItem.Name;
                storedItem.GameObject.name = storedItem.GameObjectName;
                if (storedItem.ChildIds.Count > 0)
                {
                    List <UniqueIdentifier> list4 = storedItem.GameObject.GetComponentsInChildren <UniqueIdentifier>().ToList <UniqueIdentifier>();
                    int num2 = 0;
                    while (num2 < list4.Count && num2 < storedItem.ChildIds.Count)
                    {
                        list4[num2].Id = storedItem.ChildIds[num2];
                        num2++;
                    }
                }
                if (storedItem.Children.Count > 0)
                {
                    List <StoreInformation> componentsInChildrenWithClause = JSONLevelSerializer.GetComponentsInChildrenWithClause(storedItem.GameObject);
                    this._indexDictionary.Clear();
                    foreach (StoreInformation storeInformation in componentsInChildrenWithClause)
                    {
                        if (storedItem.Children.ContainsKey(storeInformation.ClassId))
                        {
                            if (!this._indexDictionary.ContainsKey(storeInformation.ClassId))
                            {
                                this._indexDictionary[storeInformation.ClassId] = 0;
                            }
                            storeInformation.Id = storedItem.Children[storeInformation.ClassId][this._indexDictionary[storeInformation.ClassId]];
                            this._indexDictionary[storeInformation.ClassId] = this._indexDictionary[storeInformation.ClassId] + 1;
                        }
                    }
                }
            }
            catch (Exception ex2)
            {
                Debug.LogError(ex2);
                Radical.LogWarning(string.Concat(new object[]
                {
                    "Problem creating an object ",
                    storedItem.GameObjectName,
                    " with classID ",
                    storedItem.ClassId,
                    " ",
                    ex2
                }));
            }
        }
        HashSet <GameObject> loadedGameObjects = new HashSet <GameObject>();

        LevelSerializer.RaiseProgress("Initializing", 0.75f);
        foreach (JSONLevelSerializer.StoredItem storedItem2 in this.Data.StoredObjectNames)
        {
            GameObject byName = UniqueIdentifier.GetByName(storedItem2.Name);
            if (byName == null)
            {
                Radical.LogNow("Could not find " + storedItem2.GameObjectName + " " + storedItem2.Name, new object[0]);
            }
            else
            {
                loadedGameObjects.Add(byName);
                if (storedItem2.Components != null && storedItem2.Components.Count > 0)
                {
                    List <Component> list2 = (from c in byName.GetComponents <Component>()
                                              where !typeof(UniqueIdentifier).IsAssignableFrom(c.GetType())
                                              select c).ToList <Component>();
                    foreach (Component component in list2)
                    {
                        if (!storedItem2.Components.ContainsKey(component.GetType().FullName))
                        {
                            UnityEngine.Object.Destroy(component);
                        }
                    }
                }
                JSONLevelLoader.SetActive(byName, storedItem2.Active);
                if (storedItem2.setExtraData)
                {
                    byName.layer = storedItem2.layer;
                    byName.tag   = storedItem2.tag;
                }
            }
        }
        LevelSerializer.RaiseProgress("Initializing", 0.85f);
        if (this.rootObject != null && UniqueIdentifier.GetByName(this.Data.rootObject) == null)
        {
            Debug.Log("No root object has been configured");
        }
        foreach (JSONLevelSerializer.StoredItem storedItem3 in from c in this.Data.StoredObjectNames
                 where !string.IsNullOrEmpty(c.ParentName)
                 select c)
        {
            GameObject byName2 = UniqueIdentifier.GetByName(storedItem3.ParentName);
            GameObject byName3 = UniqueIdentifier.GetByName(storedItem3.Name);
            if (byName3 != null && byName2 != null)
            {
                byName3.transform.parent = byName2.transform;
            }
        }
        Time.timeScale = timeScale;
        LevelSerializer.RaiseProgress("Initializing", 1f);
        using (new Radical.Logging())
        {
            int currentProgress = 0;
            UnitySerializer.FinalProcess process;
            using (new UnitySerializer.ForceJSON())
            {
                using (new UnitySerializer.SerializationSplitScope())
                {
                    using (new UnitySerializer.SerializationScope())
                    {
                        foreach (var <> __AnonType in this.Data.StoredItems.GroupBy((JSONLevelSerializer.StoredData i) => i.Name, (string name, IEnumerable <JSONLevelSerializer.StoredData> cps) => new
                        {
                            Name = name,
                            Components = (from cp in cps
                                          where cp.Name == name
                                          select cp).GroupBy((JSONLevelSerializer.StoredData cp) => cp.Type, (string type, IEnumerable <JSONLevelSerializer.StoredData> components) => new
                            {
                                Type = type,
                                List = components.ToList <JSONLevelSerializer.StoredData>()
                            }).ToList()
                        }))
                        {
                            GameObject byName4 = UniqueIdentifier.GetByName(< > __AnonType.Name);
                            if (byName4 == null)
                            {
                                Radical.LogWarning(< > __AnonType.Name + " was null");
                            }
                            else
                            {
                                foreach (var <> __AnonType2 in < > __AnonType.Components)
                                {
                                    try
                                    {
                                        LevelSerializer.RaiseProgress("Loading", (float)(++currentProgress) / (float)this.Data.StoredItems.Count);
                                        Type type = UnitySerializer.GetTypeEx(< > __AnonType2.Type);
                                        if (type != null)
                                        {
                                            this.Last = byName4;
                                            bool flag3 = false;
                                            JSONLevelLoader.LoadData(byName4, ref flag3);
                                            JSONLevelLoader.LoadComponent(byName4, type.Name, ref flag3);
                                            if (!flag3)
                                            {
                                                List <Component> list = (from c in byName4.GetComponents(type)
                                                                         where c.GetType() == type
                                                                         select c).ToList <Component>();
                                                while (list.Count > < > __AnonType2.List.Count)
                                                {
                                                    UnityEngine.Object.DestroyImmediate(list.Last <Component>());
                                                    list.Remove(list.Last <Component>());
                                                }
                                                if (type == typeof(NavMeshAgent))
                                                {
                                                    < > __AnonType2 <string, List <JSONLevelSerializer.StoredData> > cp1 = < > __AnonType2;
Esempio n. 17
0
 private void Awake()
 {
     JSONLevelSerializer.AddPrefabPath("Resources");
     LevelSerializer.AddPrefabPath("Resources");
 }
Esempio n. 18
0
 public void Load()
 {
     JSONLevelSerializer.LoadSavedLevel(this.Data);
 }
Esempio n. 19
0
    public static void SerializeLevelToFile(string filename)
    {
        string str = JSONLevelSerializer.SerializeLevel();

        str.WriteToFile(Application.persistentDataPath + "/" + filename);
    }
Esempio n. 20
0
 public void SetProgress(long inSize, long outSize)
 {
     JSONLevelSerializer.RaiseProgress("Compression", 0.5f);
 }
Esempio n. 21
0
    public override void OnInspectorGUI()
    {
        Object obj  = PrefabUtility.GetPrefabParent(myTarget.gameObject);
        string path = AssetDatabase.GetAssetPath(myTarget.gameObject);

        if (path == "")
        {
            if (obj != null || Application.isPlaying)
            {
                if (!Application.isPlaying)
                {
                    Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GetAssetPath(obj));
                    DestroyImmediate(myTarget.gameObject);
                    Debug.LogError("IMPORTANT: Cannot put SaveObject in scene");
                }
                else
                {
                    EditorGUILayout.BeginHorizontal();
                    string buttonText = "Loaded:";
                    if (nextLoad != SaveObject.saveName)
                    {
                        buttonText = "Load:";
                    }
                    if (GUILayout.Button(buttonText))
                    {
                        if (nextLoad != "None")
                        {
                            Load();
                            resetChange();
                        }
                    }

                    nextLoad = EditorGUILayout.TextField(nextLoad);
                    EditorGUILayout.EndHorizontal();
                    if (SaveObject.saveName == "None")
                    {
                        if (GUILayout.Button("Load Default"))
                        {
                            nextLoad = "";
                            Load();
                            resetChange();
                        }
                        return;
                    }
                    EditorGUILayout.BeginHorizontal();

                    if (GUILayout.Button("Save" + (unsavedChanges? "*":"")))
                    {
                        SaveObject.Save();
                        resetChange();
                    }

                    if (GUILayout.Button("Call Refresh"))
                    {
                        MethodInfo dynMethod = myTarget.GetType().GetMethod("Refresh", BindingFlags.NonPublic | BindingFlags.Instance);
                        dynMethod.Invoke(myTarget, new object[0]);
                    }

                    if (GUILayout.Button("New Game"))
                    {
                        SaveObject.NewGame();
                        FieldInfo info = typeof(SaveObject).GetField("instance", BindingFlags.NonPublic | BindingFlags.Static);
                        Selection.activeObject = ((SaveObject)info.GetValue(null)).gameObject;
                        resetChange();
                    }
                    EditorGUILayout.EndHorizontal();
                    if (!unsavedChanges)
                    {
                        if (changeCD++ > 2 && SaveObject.saveName != "None")
                        {
                            changeCD = 0;
                            if (JSONLevelSerializer.Serialize(myTarget.gameObject) != previousSerialize)
                            {
                                unsavedChanges = true;
                                changeCD       = -10000000;
                            }
                        }
                    }
                }
            }
            else
            {
                if (GUILayout.Button("Place In Project"))
                {
                    string folder = "Resources";
                    if (!System.IO.Directory.Exists(Application.dataPath + "/" + folder))
                    {
                        AssetDatabase.CreateFolder("Assets", folder);
                    }
                    string fullPath = "Assets/" + folder + "/" + myTarget.gameObject.name + ".prefab";
                    obj = PrefabUtility.CreatePrefab(fullPath, myTarget.gameObject);
                    Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(fullPath);
                    DestroyImmediate(myTarget.gameObject);
                }
            }
        }
        else
        {
            GUIStyle style = new GUIStyle();
            style.font      = EditorStyles.boldFont;
            style.normal    = EditorStyles.boldLabel.normal;
            style.alignment = TextAnchor.MiddleCenter;
            EditorGUILayout.LabelField("New Game Stats", style);
            if (GUILayout.Button("Get Initialization Script"))
            {
                string resFol = "/Resources/";
                if (path.Contains(resFol))
                {
                    int begin = path.IndexOf(resFol) + resFol.Length;
                    path = path.Substring(begin, path.Length - begin - 7);
                    EditorGUIUtility.systemCopyBuffer = "SaveObject.Initialize(\"" + path + "\");";
                }
                else
                {
                    EditorGUIUtility.systemCopyBuffer = "SaveObject.Initialize([LINK TO SAVER PREFAB]);";
                }
                Debug.LogWarning(EditorGUIUtility.systemCopyBuffer + " << In the clipboard, copy paste in your script to initialize");
            }
        }
    }