Beispiel #1
0
    public override object Load(object[] data, object instance)
    {
        if (instance != null)
        {
            return(instance);
        }
#if US_LOGGING
        if (!((bool)data [1]))
        {
            Radical.Log("[[Disabled, will not be set]]");
        }
        Radical.Log("GameObject: {0}", data [0]);
#endif
        if (data.Length > 3)
        {
            var asset = SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]) as GameObject;
            return(asset);
        }
        return(instance ?? new UnitySerializer.DeferredSetter((d) => {
            return UniqueIdentifier.GetByName((string)data [0]);
        })
        {
            enabled = (bool)data [1]
        });
    }
Beispiel #2
0
    public override IEnumerable <object> Save(Component target)
    {
        SaveGameManager.AssetReference assetId = SaveGameManager.Instance.GetAssetId(target);
        if (assetId.index != -1)
        {
            return(new object[]
            {
                null,
                true,
                target.GetType().FullName,
                assetId
            });
        }
        int num = target.gameObject.GetComponents(target.GetType()).FindIndex((Component c) => c == target);

        if (UniqueIdentifier.GetByName(target.gameObject.GetId()) != null)
        {
            return(new object[]
            {
                target.gameObject.GetId(),
                true,
                target.GetType().FullName,
                string.Empty,
                num
            });
        }
        return(new object[]
        {
            target.gameObject.GetId(),
            false,
            target.GetType().FullName,
            string.Empty,
            num
        });
    }
Beispiel #3
0
    public override IEnumerable <object> Save(GameObject target)
    {
        //Is this a reference to a prefab
        var assetId = SaveGameManager.Instance.GetAssetId(target);

        if (assetId.index != -1)
        {
            return(new object[] { 0, true, null, assetId });
        }
        return(new object[] { target.GetId(), UniqueIdentifier.GetByName(target.gameObject.GetId()) != null /* Identify a prefab */ });
    }
Beispiel #4
0
    IEnumerable <LevelSerializer.StoredItem> IEGetByNameNull()
    {
        int index = 0;

        while (index < Data.StoredObjectNames.Count)
        {
            var c = Data.StoredObjectNames[index++];
            if ((UniqueIdentifier.GetByName(c.Name) == null))
            {
                yield return(c);
            }
        }
    }
Beispiel #5
0
 public override object Load(object[] data, object instance)
 {
     if (data[3] != null && data[3].GetType() == typeof(SaveGameManager.AssetReference))
     {
         return(SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]));
     }
     if (data.Length == 5)
     {
         return(new UnitySerializer.DeferredSetter(delegate(Dictionary <string, object> d)
         {
             GameObject byName = UniqueIdentifier.GetByName((string)data[0]);
             if (byName == null)
             {
                 Debug.LogError(string.Concat(new object[]
                 {
                     "Could not find reference to ",
                     data[0],
                     " a ",
                     (string)data[2]
                 }));
                 return null;
             }
             Component[] components = byName.GetComponents(UnitySerializer.GetTypeEx(data[2]));
             if (components.Length == 0)
             {
                 return null;
             }
             if (components.Length <= (int)data[4])
             {
                 data[4] = 0;
             }
             return (!(byName != null)) ? null : components[(int)data[4]];
         })
         {
             enabled = (bool)data[1]
         });
     }
     return(new UnitySerializer.DeferredSetter(delegate(Dictionary <string, object> d)
     {
         GameObject byName = UniqueIdentifier.GetByName((string)data[0]);
         return (!(byName != null)) ? null : byName.GetComponent(UnitySerializer.GetTypeEx(data[2]));
     })
     {
         enabled = (bool)data[1]
     });
 }
Beispiel #6
0
    public override object Load(object[] data, object instance)
    {
#if US_LOGGING
        if (!((bool)data [1]))
        {
            Radical.Log("[[Disabled, will not be set]]");
        }
        Radical.Log("Component: {0}.{1}", data [0], data [2]);
#endif

        if (data[3] != null && data[3].GetType() == typeof(SaveGameManager.AssetReference))
        {
            return(SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]));
        }
        if (data.Length == 5)
        {
            return(new UnitySerializer.DeferredSetter((d) => {
                var item = UniqueIdentifier.GetByName((string)data [0]);
                if (item == null)
                {
                    Debug.LogError("Could not find reference to " + data[0] + " a " + (string)data[2]);
                    return null;
                }
                var allComponentsOfType = item.GetComponents(UnitySerializer.GetTypeEx(data[2]));
                if (allComponentsOfType.Length == 0)
                {
                    return null;
                }
                if (allComponentsOfType.Length <= (int)data[4])
                {
                    data[4] = 0;
                }
                return item != null ? allComponentsOfType[(int)data[4]] : null;
            })
            {
                enabled = (bool)data [1]
            });
        }
        return(new UnitySerializer.DeferredSetter((d) => {
            var item = UniqueIdentifier.GetByName((string)data [0]);
            return item != null ? item.GetComponent(UnitySerializer.GetTypeEx(data [2])) : null;
        })
        {
            enabled = (bool)data [1]
        });
    }
    public override object Load(object[] data, object instance)
    {
#if US_LOGGING
        if (!((bool)data [1]))
        {
            Radical.Log("[[Disabled, will not be set]]");
        }
        Radical.Log("Component: {0}.{1}", data [0], data [2]);
#endif
        return(new UnitySerializer.DeferredSetter((d) => {
            var item = UniqueIdentifier.GetByName((string)data [0]);
            return item != null ? item.GetComponent(Type.GetType((string)data [2])) : null;
        })
        {
            enabled = (bool)data [1]
        });
    }
Beispiel #8
0
    public static bool HasParent(UniqueIdentifier i, string id)
    {
        var scan = UniqueIdentifier.GetByName(i.Id).transform;

        while (scan != null)
        {
            UniqueIdentifier ui;
            if ((ui = scan.GetComponent <UniqueIdentifier>()) != null)
            {
                if (id == ui.Id)
                {
                    return(true);
                }
            }
            scan = scan.parent;
        }
        return(false);
    }
 public override IEnumerable <object> Save(GameObject target)
 {
     SaveGameManager.AssetReference assetId = SaveGameManager.Instance.GetAssetId(target);
     if (assetId.index != -1)
     {
         return(new object[]
         {
             0,
             true,
             null,
             assetId
         });
     }
     return(new object[]
     {
         target.GetId(),
         UniqueIdentifier.GetByName(target.gameObject.GetId()) != null
     });
 }
Beispiel #10
0
    public override IEnumerable <object> Save(Component target)
    {
        //Is this a reference to a prefab
        var assetId = SaveGameManager.Instance.GetAssetId(target);

        if (assetId.index != -1)
        {
            return(new object[] { null, true, target.GetType().FullName, assetId });
        }

        var index = target.gameObject.GetComponents(target.GetType()).FindIndex(c => c == target);

        if (UniqueIdentifier.GetByName(target.gameObject.GetId()) != null)
        {
            return(new object[] { target.gameObject.GetId(), true, target.GetType().FullName, "", index /* Identify a prefab */ });
        }
        else
        {
            return(new object[] { target.gameObject.GetId(), false, target.GetType().FullName, "", index /* Identify a prefab */ });
        }
    }
    public override object Load(object[] data, object instance)
    {
        if (instance != null)
        {
            return(instance);
        }
#if US_LOGGING
        if (!((bool)data [1]))
        {
            Radical.Log("[[Disabled, will not be set]]");
        }
        Radical.Log("GameObject: {0}", data [0]);
#endif

        return(instance ?? new UnitySerializer.DeferredSetter((d) => {
            return UniqueIdentifier.GetByName((string)data [0]);
        })
        {
            enabled = (bool)data [1]
        });
    }
Beispiel #12
0
    List <UniqueIdentifier> FlaggedObjectsAddRange()
    {
        List <UniqueIdentifier> retList = new List <UniqueIdentifier>();

        //Data.StoredObjectNames.Select(c => UniqueIdentifier.GetByName(c.Name)).Where(c => c != null).Select(c => c.GetComponent<UniqueIdentifier>());

        foreach (var c in Data.StoredObjectNames)
        {
            if (c != null)
            {
                GameObject goui = UniqueIdentifier.GetByName(c.Name);

                if (goui != null)
                {
                    retList.Add(goui.GetComponent <UniqueIdentifier>());
                }
            }
        }

        return(retList);
    }
 public override IEnumerable <object> Save(Component target)
 {
     return(new object[] { target.gameObject.GetId(), UniqueIdentifier.GetByName(target.gameObject.GetId()) != null, target.GetType().AssemblyQualifiedName, "" /* Identify a prefab */ });
 }
 public override IEnumerable <object> Save(GameObject target)
 {
     return(new object[] { target.GetId(), UniqueIdentifier.GetByName(target.gameObject.GetId()) != null /* Identify a prefab */ });
 }
 public override object Load(object[] data, object instance)
 {
     if (instance != null)
     {
         return(instance);
     }
     if (data.Length > 3)
     {
         return(SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]) as GameObject);
     }
     return(instance ?? new UnitySerializer.DeferredSetter((Dictionary <string, object> d) => UniqueIdentifier.GetByName((string)data[0]))
     {
         enabled = (bool)data[1]
     });
 }
Beispiel #16
0
    void UnitySerializerAddFinalAction()
    {
        if (global_list == null)
        {
            return;
        }
        if (global_compList == null)
        {
            return;
        }
        if (global_compType == null)
        {
            return;
        }
        if (global_tp == null)
        {
            return;
        }
        if (global_tname == null)
        {
            return;
        }

        //UnitySerializer.AddFinalAction(() =>
        {
            var g = UniqueIdentifier.GetByName(global_tname);
            //var nlist = g.GetComponents(global_tp).Where(c => c.GetType() == global_tp).ToList();

            var nlist = GetTypeComponents(g, global_tp);

            while (nlist.Count < global_compList.Count)
            {
                try
                {
                    nlist.Add(g.AddComponent(global_tp));
                }
                catch
                {
                }
            }
            //list = list.Where(l => l != null).ToList();
            List <Component> list = new List <Component>();

            foreach (var l in global_list)
            {
                if (l != null)
                {
                    list.Add(l);
                }
            }

            global_list.Clear();
            global_list.AddRange(list);


            //Now deserialize the items back in
            for (var i = 0; i < nlist.Count; i++)
            {
                if (LevelSerializer.CustomSerializers.ContainsKey(global_tp))
                {
                    LevelSerializer.CustomSerializers[global_tp].Deserialize((byte[])global_compList[i].Data, nlist[i]);
                }
                else
                {
                    UnitySerializer.DeserializeInto(global_compList[i].Data, nlist[i]);
                }
                Debug.Log("here");
                LoadedComponent(nlist[i]);
                Debug.Log(LoadedComponent.Target);
            }
        }
        //);


        global_list     = null;
        global_compList = null;
        global_compType = null;
        global_tp       = null;
        global_tname    = null;
    }
Beispiel #17
0
    public IEnumerator Load(int numberOfFrames, float timeScale = 0f)
    {
        LevelLoader.loadingCount++;
        float oldFixedTime = Time.fixedDeltaTime;

        Time.fixedDeltaTime = 9f;
        for (;;)
        {
            if (LevelSerializer.LevelLoadingOperation == null || LevelSerializer.LevelLoadingOperation.isDone)
            {
                int num;
                numberOfFrames = (num = numberOfFrames) - 1;
                if (num <= 0)
                {
                    break;
                }
            }
            yield return(new WaitForEndOfFrame());
        }
        LevelSerializer.LevelLoadingOperation = null;
        if (LevelSerializer.ShouldCollect && timeScale == 0f)
        {
            GC.Collect();
        }
        LevelSerializer.RaiseProgress("Initializing", 0f);
        if (this.Data.rootObject != null)
        {
            Debug.Log((!this.Data.StoredObjectNames.Any((LevelSerializer.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)
            {
                LevelLoader $this = this.$this;
                return(this.$this.Data.StoredObjectNames.All((LevelSerializer.StoredItem sn) => sn.Name != n.Id));
            }).ToList <UniqueIdentifier>())
            {
                try
                {
                    bool flag = false;
                    LevelLoader.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>();

        flaggedObjects.AddRange(from c in this.Data.StoredObjectNames
                                select UniqueIdentifier.GetByName(c.Name) into c
                                where c != null
                                select c.GetComponent <UniqueIdentifier>());
        LevelSerializer.RaiseProgress("Initializing", 0.25f);
        Vector3 position = new Vector3(0f, 2000f, 2000f);

        foreach (LevelSerializer.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;
                    LevelLoader.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 = LevelSerializer.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)
            {
                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 (LevelSerializer.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);
                        }
                    }
                }
                LevelLoader.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 (LevelSerializer.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);
        int count           = 0;
        int currentProgress = 0;

        UnitySerializer.FinalProcess process;
        try
        {
            if (this.useJSON)
            {
                UnitySerializer.ForceJSONSerialization();
            }
            using (new UnitySerializer.SerializationSplitScope())
            {
                using (new UnitySerializer.SerializationScope())
                {
                    foreach (var <> __AnonType in this.Data.StoredItems.GroupBy((LevelSerializer.StoredData i) => i.Name, (string name, IEnumerable <LevelSerializer.StoredData> cps) => new
                    {
                        Name = name,
                        Components = (from cp in cps
                                      where cp.Name == name
                                      select cp).GroupBy((LevelSerializer.StoredData cp) => cp.Type, (string type, IEnumerable <LevelSerializer.StoredData> components) => new
                        {
                            Type = type,
                            List = components.ToList <LevelSerializer.StoredData>()
                        }).ToList()
                    }))
                    {
                        count++;
                        GameObject byName4 = UniqueIdentifier.GetByName(< > __AnonType.Name);
                        if (byName4 == null)
                        {
                            Radical.LogWarning(< > __AnonType.Name + " was null");
                        }
                        else
                        {
                            foreach (var <> __AnonType2 in < > __AnonType.Components)
                            {
                                try
                                {
                                    if (++currentProgress % 100 == 0)
                                    {
                                        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;
                                        LevelLoader.LoadData(byName4, ref flag3);
                                        LevelLoader.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 <LevelSerializer.StoredData> > cp1 = < > __AnonType2;
                                                < > __AnonType3 <string, List <<> __AnonType2 <string, List <LevelSerializer.StoredData> > >> item1 = < > __AnonType;
                                                int    l;
                                                Action action = delegate
                                                {
Beispiel #18
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>();

        flaggedObjects.AddRange(Data.StoredObjectNames.Select(c => UniqueIdentifier.GetByName(c.Name)).Where(c => c != null).Select(c => c.GetComponent <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 = LevelSerializer.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.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 (LevelSerializer.CustomSerializers.ContainsKey(tp))
                                                {
                                                    LevelSerializer.CustomSerializers[tp].Deserialize((byte[])comp.List[i].Data, nlist[i]);
                                                }
                                                else
                                                {
                                                    UnitySerializer.DeserializeInto(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 (LevelSerializer.CustomSerializers.ContainsKey(type))
                                        {
                                            LevelSerializer.CustomSerializers[type].Deserialize(cp.List[i].Data, list[i]);
                                        }
                                        else
                                        {
                                            UnitySerializer.DeserializeInto(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);
            }


            LevelSerializer.IsDeserializing = false;
            _loading = false;
            RoomManager.loadingRoom = false;
            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);
        }
    }
Beispiel #19
0
    public IEnumerator Load(int numberOfFrames)
    {
        //Need to wait while the base level is prepared, it takes 2 frames
        while (numberOfFrames-- > 0)
        {
            yield return(new WaitForEndOfFrame());
        }
        if (LevelSerializer.ShouldCollect)
        {
            GC.Collect();
        }

        LevelSerializer.RaiseProgress("Initializing", 0);

        //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.Any(sn => sn.Name == n.Id)).ToList())
            {
                try
                {
                    bool cancel = false;
                    OnDestroyObject(go.gameObject, ref cancel);
                    if (!cancel)
                    {
                        GameObject.Destroy(go.gameObject);
                    }
                }
                catch (Exception e)
                {
                    Radical.LogWarning("Problem destroying object " + go.name + " " + e.ToString());
                }
            }
        }

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


        //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 && !string.IsNullOrEmpty(c.ClassId)))
        {
            try
            {
                var  pf     = LevelSerializer.AllPrefabs[sto.ClassId];
                bool cancel = false;
                CreateGameObject(pf as GameObject, ref cancel);
                if (cancel)
                {
                    continue;
                }

                sto.GameObject = Instantiate(pf) as GameObject;
                sto.GameObject.GetComponent <UniqueIdentifier>().Id = sto.Name;
                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 = LevelSerializer.GetComponentsInChildrenWithClause(sto.GameObject);
                    indexDictionary.Clear();
                    foreach (var c in list)
                    {
                        if (sto.Children.ContainsKey(c.ClassId))
                        {
                            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)
            {
                Radical.LogWarning("Problem creating " + sto.GameObjectName + " with classID " + sto.ClassId + " " + e.ToString());
            }
        }
        HashSet <GameObject> 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>().ToList();
                    foreach (var comp in all)
                    {
                        if (!so.Components.ContainsKey(comp.GetType().AssemblyQualifiedName))
                        {
                            Destroy(comp);
                        }
                    }
                }
                SetActive(go, so.Active);
            }
        }

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


        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
        yield return(new WaitForEndOfFrame());

        yield return(new WaitForEndOfFrame());

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


        using (new Radical.Logging())
        {
            var currentProgress = 0;

            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);
                            Type type = Type.GetType(cp.Type);
                            if (type == null)
                            {
                                continue;
                            }
                            Last = go;
                            bool 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)
                            {
                                Component.DestroyImmediate(list.Last());
                                list.Remove(list.Last());
                            }
                            if (type == typeof(NavMeshAgent))
                            {
                                Action perform = () => {
                                    var comp  = cp;
                                    var tp    = type;
                                    var tname = item.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 (LevelSerializer.CustomSerializers.ContainsKey(tp))
                                            {
                                                LevelSerializer.CustomSerializers [tp].Deserialize(comp.List [i].Data, nlist [i]);
                                            }
                                            else
                                            {
                                                UnitySerializer.DeserializeInto(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 (LevelSerializer.CustomSerializers.ContainsKey(type))
                                    {
                                        LevelSerializer.CustomSerializers [type].Deserialize(cp.List [i].Data, list [i]);
                                    }
                                    else
                                    {
                                        UnitySerializer.DeserializeInto(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
                }

                //yield return null;
                //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();
                Resources.UnloadUnusedAssets();
                if (LevelSerializer.ShouldCollect)
                {
                    GC.Collect();
                }

                yield return(null);

                yield return(null);


                UnitySerializer.InformDeserializedObjects();

                //Flag that we aren't deserializing
                LevelSerializer.IsDeserializing = false;

                //Tell the world that the level has been loaded
                LevelSerializer.InvokeDeserialized();
                whenCompleted(loadedGameObjects.ToList());
                loading = false;
                RoomManager.loadingRoom = false;
                //Get rid of the current object that is holding this level loader, it was
                //created solely for the purpose of running this script
                GameObject.Destroy(this.gameObject, 1.1f);
            }
        }
    }