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); } }
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;