public static void Example()
    {
        //
        Debug.Log ("--- UnitySerializer Example ---");
        Color color = new Color(0.3f,0.1f,0.5f,0.001f);
        Vector2 point = UnityEngine.Random.insideUnitCircle;
        Vector3 position = UnityEngine.Random.onUnitSphere;
        Quaternion quaternion = UnityEngine.Random.rotation;
        float f = UnityEngine.Random.value;
        int i = UnityEngine.Random.Range (0, 10000);
        double d = (double)UnityEngine.Random.Range (0, 10000);
        string s = "Brundle Fly";
        bool b = UnityEngine.Random.value < 0.5f ? true : false;
        System.Type type = typeof(UnitySerializer);

        //
        Debug.Log ("--- Before ---");
        Debug.Log (point + " " + position + " " + quaternion + " " + f + " " + i + " " + d + " " + s + " " + b + " " + type);

        //
        Debug.Log ("--- Serialize ---");
        UnitySerializer us = new UnitySerializer ();
        us.Serialize(color);
        us.Serialize (point);
        us.Serialize (position);
        us.Serialize (quaternion);
        us.Serialize (f);
        us.Serialize (i);
        us.Serialize (d);
        us.Serialize (s);
        us.Serialize (b);
        us.Serialize (type);
        byte[] byteArray = us.ByteArray;

        // the array must be deserialized in the same order as it was serialized
        Debug.Log ("--- Deserialize ---");

        UnitySerializer uds = new UnitySerializer (byteArray);
        Color color2 = uds.DeserializeColor();
        Vector2 point2 = uds.DeserializeVector2 ();
        Vector3 position2 = uds.DeserializeVector3 ();
        Quaternion quaternion2 = uds.DeserializeQuaternion ();
        float f2 = uds.DeserializeFloat ();
        int i2 = uds.DeserializeInt ();
        double d2 = uds.DeserializeDouble ();
        string s2 = uds.DeserializeString ();
        bool b2 = uds.DeserializeBool ();
        System.Type type2 = uds.DeserializeType ();

        //
        Debug.Log ("--- After ---");
        Debug.Log (color2 + " " + point2 + " " + position2 + " " + quaternion2 + " " + f2 + " " + i2 + " " + d2 + " " + s2 + " " + b2 + " " + type2);
    }
Beispiel #2
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]
        });
    }
Beispiel #3
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 #4
0
        public object ReadSimpleValue(Type type)
        {
            string name = type.Name;

            if (name != null)
            {
                if (name == "DateTime")
                {
                    return(DateTime.Parse((string)this._reader.Value));
                }
                if (name == "String")
                {
                    return(UnitySerializer.UnEscape((string)this._reader.Value));
                }
            }
            return(this._reader.Value);
        }
Beispiel #5
0
        public void StartDeserializing()
        {
            UnitySerializer.PushKnownTypes();
            UnitySerializer.PushPropertyNames();
            MemoryStream memoryStream = new MemoryStream(this.Data);
            BinaryReader binaryReader = new BinaryReader(memoryStream);
            string       text         = binaryReader.ReadString();

            UnitySerializer.currentVersion = int.Parse(text.Substring(4));
            if (UnitySerializer.currentVersion >= 3)
            {
                UnitySerializer.Verbose = binaryReader.ReadBoolean();
            }
            int num = binaryReader.ReadInt32();

            for (int i = 0; i < num; i++)
            {
                string text2 = binaryReader.ReadString();
                Type   type  = UnitySerializer.GetTypeEx(text2);
                if (type == null)
                {
                    UnitySerializer.TypeMappingEventArgs typeMappingEventArgs = new UnitySerializer.TypeMappingEventArgs
                    {
                        TypeName = text2
                    };
                    UnitySerializer.InvokeMapMissingType(typeMappingEventArgs);
                    type = typeMappingEventArgs.UseType;
                }
                if (type == null)
                {
                    throw new ArgumentException(string.Format("Cannot reference type {0} in this context", text2));
                }
                UnitySerializer._knownTypesList.Add(type);
            }
            num = binaryReader.ReadInt32();
            for (int j = 0; j < num; j++)
            {
                UnitySerializer._propertyList.Add(binaryReader.ReadString());
            }
            byte[] buffer = binaryReader.ReadBytes(binaryReader.ReadInt32());
            this._myStream = new MemoryStream(buffer);
            this._reader   = new BinaryReader(this._myStream);
            binaryReader.Close();
            memoryStream.Close();
        }
 public byte[] Serialize(Component component)
 {
     byte[] result;
     using (new UnitySerializer.SerializationSplitScope())
     {
         Renderer renderer = (Renderer)component;
         SerializeRenderer.StoredInformation storedInformation = new SerializeRenderer.StoredInformation();
         storedInformation.Enabled = renderer.enabled;
         if ((SerializeRenderer.Store = renderer.GetComponent <StoreMaterials>()) != null)
         {
             storedInformation.materials = renderer.materials.ToList <Material>();
         }
         byte[] array = UnitySerializer.Serialize(storedInformation);
         SerializeRenderer.Store = null;
         result = array;
     }
     return(result);
 }
Beispiel #7
0
    public byte[] Serialize(Component component)
    {
        var agent = (NavMeshAgent)component;

        return(UnitySerializer.Serialize(new StoredInfo {
            x = agent.destination.x,
            y = agent.destination.y,
            z = agent.destination.z,
            speed = agent.speed,
            acceleration = agent.acceleration,
            angularSpeed = agent.angularSpeed,
            height = agent.height,
            offset = agent.baseOffset,
            hasPath = agent.hasPath,
            offMesh = agent.isOnOffMeshLink,
            passable = agent.walkableMask
        }));
    }
Beispiel #8
0
    /// <summary>
    /// Loads the specified data immediately
    /// </summary>
    /// <param name='data'>
    /// Data to load
    /// </param>
    /// <param name='dontDeleteExistingItems'>
    /// Whether items that are not in the file should be deleted
    /// </param>
    /// <param name='showLoadingGUI'>
    /// Show the white flash
    /// </param>
    /// <param name='complete'>
    /// Function to call when complete
    /// </param>
    /// <exception cref='ArgumentException'>
    /// Is thrown when an argument passed to a method is invalid.
    /// </exception>
    public static void LoadNow(string data, bool dontDeleteExistingItems, bool showLoadingGUI, Action <JSONLevelLoader> complete)
    {
        if (data == null)
        {
            throw new ArgumentException("data parameter must be provided");
        }
        //Create a level loader
        var l      = new GameObject();
        var loader = l.AddComponent <JSONLevelLoader>();

        loader.showGUI = showLoadingGUI;
        var ld = UnitySerializer.JSONDeserialize <JSONLevelSerializer.LevelData> (data);

        loader.Data       = ld;
        loader.DontDelete = dontDeleteExistingItems;
        //Get the loader to do its job
        loader.StartCoroutine(PerformLoad(loader, complete));
    }
Beispiel #9
0
    /// <summary>
    ///   Loads the saved level.
    /// </summary>
    /// <param name='data'> The data describing the level to load </param>
    public static JSONLevelLoader LoadSavedLevel(string data)
    {
        IsDeserializing = true;
        LevelSerializer.IsDeserializing = true;
        SaveGameManager.Loaded();
        var go = new GameObject();

        UnityEngine.Object.DontDestroyOnLoad(go);
        var loader = go.AddComponent <JSONLevelLoader>();

        loader.Data = UnitySerializer.JSONDeserialize <LevelData>(UnitySerializer.UnEscape(data));

        if (Application.loadedLevelName != loader.Data.Name)
        {
            Application.LoadLevel(loader.Data.Name);
        }
        return(loader);
    }
 /// <summary>
 ///   Suspends the serialization. Must resume as many times as you suspend
 /// </summary>
 public static void SuspendSerialization()
 {
     if (_suspensionCount == 0)
     {
         SuspendingSerialization();
         if (SerializationMode == SerializationModes.CacheSerialization)
         {
             _cachedState = CreateSaveEntry("resume", true);
             if (SaveResumeInformation)
             {
                 FilePrefs.SetString(PlayerName + "__RESUME__",
                                     Convert.ToBase64String(UnitySerializer.Serialize(_cachedState)));
                 FilePrefs.Save();
             }
         }
     }
     _suspensionCount++;
 }
Beispiel #11
0
    void loadGraphFromBinFile(string positionsFileName, string matrixFileName, string pathFileName, string rotationFileName)
    {
        //load saved graph values
        UnitySerializer usPositions = new UnitySerializer();
        UnitySerializer usMatrix    = new UnitySerializer();
        UnitySerializer usPath      = new UnitySerializer();
        UnitySerializer usRotation  = new UnitySerializer();

        byte[] dataPositions = usPositions.LoadFromFile(positionsFileName);
        byte[] dataMatrix    = usMatrix.LoadFromFile(matrixFileName);
        byte[] dataPath      = usPath.LoadFromFile(pathFileName);
        byte[] dataRotation  = usRotation.LoadFromFile(rotationFileName);

        verticesToLink = getListV3fromBinaryData(dataPositions, usPositions);
        adj            = getIntListFromBinaryData(dataMatrix, usMatrix);
        path           = getIntListFromBinaryData(dataPath, usPath);
        myRotation     = usRotation.DeserializeQuaternion(dataRotation);
    }
Beispiel #12
0
    private static void PerformSave(string name, bool urgent)
    {
        var newGame = CreateSaveEntry(name, urgent);

        SavedGames[PlayerName].Insert(0, newGame);


        while (SavedGames.Count > MaxGames)
        {
            SavedGames[PlayerName].RemoveAt(SavedGames.Count - 1);
        }

        SaveDataToPlayerPrefs();

        PlayerPrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(newGame)));

        GameSaved();
    }
Beispiel #13
0
        private void EncodeType(object item, Type storedType)
        {
            if (item == null)
            {
                this.WriteSimpleValue(65534);
                return;
            }
            Type type = item.GetType();

            if (storedType == null || storedType != item.GetType() || UnitySerializer.Verbose)
            {
                ushort typeId = UnitySerializer.GetTypeId(type);
                this.WriteSimpleValue(typeId);
            }
            else
            {
                this.WriteSimpleValue(ushort.MaxValue);
            }
        }
Beispiel #14
0
        public void ExportAllToJson(string resourceAssetsPath, string outputDirectory)
        {
            using (AssetsFile file = AssetsFile.Open(resourceAssetsPath))
            {
                var assetSerializer = new UnitySerializer(file);

                foreach (DataType dType in types)
                {
                    LogCallback?.Invoke(dType.AssetName);
                    AssetInfo info = file.GetAssetByName(dType.AssetName);

                    var textAsset = assetSerializer.Deserialize <TextAsset>(info);
                    var obj       = skylessSerializer.DeserializeBinary(dType.TypeName, textAsset.m_Data);

                    string jsonPath = Path.Combine(outputDirectory, $"{dType.AssetName}.json");
                    skylessSerializer.SerializeJson(jsonPath, obj);
                }
            }
        }
Beispiel #15
0
        public void FinishedSerializing()
        {
            this._writer.Flush();
            this._writer.Close();
            this._myStream.Flush();
            byte[] array = this._myStream.ToArray();
            this._myStream.Close();
            this._myStream = null;
            MemoryStream memoryStream = new MemoryStream();
            BinaryWriter binaryWriter = new BinaryWriter(memoryStream);

            binaryWriter.Write("SerV10");
            binaryWriter.Write(UnitySerializer.Verbose);
            if (UnitySerializer.SerializationScope.IsPrimaryScope)
            {
                binaryWriter.Write(UnitySerializer._knownTypesLookup.Count);
                foreach (Type type in UnitySerializer._knownTypesLookup.Keys)
                {
                    binaryWriter.Write(type.FullName);
                }
                binaryWriter.Write(UnitySerializer._propertyLookup.Count);
                foreach (string value in UnitySerializer._propertyLookup.Keys)
                {
                    binaryWriter.Write(value);
                }
            }
            else
            {
                binaryWriter.Write(0);
                binaryWriter.Write(0);
            }
            binaryWriter.Write(array.Length);
            binaryWriter.Write(array);
            binaryWriter.Flush();
            binaryWriter.Close();
            memoryStream.Flush();
            this.Data = memoryStream.ToArray();
            memoryStream.Close();
            this._writer = null;
            this._reader = null;
            UnitySerializer.PopKnownTypes();
            UnitySerializer.PopPropertyNames();
        }
Beispiel #16
0
	public override IEnumerable<object> Save(object target)
	{
		SaveGameManager.AssetReference assetId = SaveGameManager.Instance.GetAssetId(target as UnityEngine.Object);
		if (assetId.index == -1)
		{
			byte[] array = UnitySerializer.SerializeForDeserializeInto(target);
			return new object[]
			{
				true,
				target.GetType().FullName,
				array
			};
		}
		return new object[]
		{
			false,
			assetId
		};
	}
 private static object GetVanilla(Type type)
 {
     try
     {
         object vanilla = null;
         lock (Vanilla)
         {
             if (!Vanilla.TryGetValue(type, out vanilla))
             {
                 vanilla       = UnitySerializer.CreateObject(type);
                 Vanilla[type] = vanilla;
             }
         }
         return(vanilla);
     }
     catch
     {
         return(null);
     }
 }
Beispiel #18
0
    public void Deserialize(byte[] data, Component instance)
    {
        var animation = (Animation)instance;

        animation.Stop();
        var list = UnitySerializer.Deserialize <List <StoredState> >(data);

        foreach (var entry in list)
        {
            if (entry.name.Contains(" - Queued Clone"))
            {
                var newState = animation.PlayQueued(entry.name.Replace(" - Queued Clone", ""));
                UnitySerializer.DeserializeInto(entry.data, newState);
            }
            else
            {
                UnitySerializer.DeserializeInto(entry.data, animation[entry.name]);
            }
        }
    }
Beispiel #19
0
    public object GetAsset(SaveGameManager.AssetReference id)
    {
        if (id.index == -1)
        {
            return(null);
        }
        object result;

        try
        {
            Type typeEx = UnitySerializer.GetTypeEx(id.type);
            Index <string, List <UnityEngine.Object> > index;
            if (!this.assetReferences.TryGetValue(typeEx, out index))
            {
                index = (this.assetReferences[typeEx] = new Index <string, List <UnityEngine.Object> >());
                IEnumerable <UnityEngine.Object> enumerable = Resources.FindObjectsOfTypeAll(typeEx).Except(UnityEngine.Object.FindObjectsOfType(typeEx));
                foreach (UnityEngine.Object current in enumerable)
                {
                    index[current.name].Add(current);
                }
            }
            List <UnityEngine.Object> list;
            if (!index.TryGetValue(id.name, out list))
            {
                result = null;
            }
            else if (id.index >= list.Count)
            {
                result = null;
            }
            else
            {
                result = list[id.index];
            }
        }
        catch
        {
            result = null;
        }
        return(result);
    }
    private static void PerformSave(string name, bool urgent)
    {
        var newGame = CreateSaveEntry(name, urgent);

        SavedGames[PlayerName].Insert(0, newGame);


        while (SavedGames[PlayerName].Count > MaxGames)
        {
            SavedGames[PlayerName].RemoveAt(SavedGames.Count - 1);
        }
        string output = UnitySerializer.JSONSerialize(newGame);

        System.IO.File.WriteAllText(@"C:\dev\savegame.json", output);

        SaveDataToPlayerPrefs();

        PlayerPrefs.SetString(PlayerName + "JSON__RESUME__", UnitySerializer.JSONSerialize(newGame));
        PlayerPrefs.Save();
        GameSaved();
    }
    public static void Deserialize(string data)
    {
        JSONLevelSerializer.LevelData Data = UnitySerializer.JSONDeserialize <JSONLevelSerializer.LevelData>(data);
        GameObject go = UniqueIdentifier.identifier.gameObject;
        int        i  = Data.StoredItem.Count;

        while (i-- > 0)
        {
            JSONLevelSerializer.StoredData cp = Data.StoredItem[i];
            Type      type      = UnitySerializer.GetTypeEx(cp.Type);
            Component component = go.GetComponent(type);
            if (JSONLevelSerializer.CustomSerializers.ContainsKey(type))
            {
                JSONLevelSerializer.CustomSerializers[type].Deserialize(Encoding.Default.GetBytes(cp.Data), component);
            }
            else
            {
                UnitySerializer.JSONDeserializeInto(cp.Data, component);
            }
        }
    }
Beispiel #22
0
 public void WriteSimpleValue(object value)
 {
     if (value is string)
     {
         _json.AppendFormat("\"{0}\"", UnitySerializer.Escape((string)value));
     }
     else if (value is DateTime)
     {
         _json.AppendFormat("\"{0}\"", value);
     }
     else if (value is bool)
     {
         _json.Append(((bool)value) ? "true" : "false");
     }
     else if (value is float || value is double)
     {
         _json.AppendFormat("{0:0.00000000}", value);
     }
     else
     {
         _json.AppendFormat("{0}", value);
     }
 }
Beispiel #23
0
        public void WriteSimpleValue(object value)
        {
            if (value is string)
            {
                /*if(((string)value).Length > 201) {
                 *                      var val = (string)value;
                 *                      var data = UnitySerializer.Escape((string)value);
                 *                      data = data.Substring(data.Length - 200);
                 *                      val = val.Substring(val.Length - 200);
                 *                      UnityEngine.Debug.Log(data + "\n\n\n" + val);
                 *              } */
                _json.AppendFormat("\"{0}\"", UnitySerializer.Escape((string)value));

                /*var upd = _json.ToString();
                 *              if(_json.Length>20)
                 *              {
                 *                      upd = upd.Substring(upd.Length-20);
                 *                      UnityEngine.Debug.Log(upd);
                 *              }*/
            }
            else if (value is DateTime)
            {
                _json.AppendFormat("\"{0}\"", value);
            }
            else if (value is bool)
            {
                _json.Append(((bool)value) ? "true" : "false");
            }
            else if (value is float || value is double)
            {
                _json.AppendFormat("{0:0.00000000}", value);
            }
            else
            {
                _json.AppendFormat("{0}", value);
            }
        }
Beispiel #24
0
    public void Deserialize(byte[] data, Component instance)
    {
        NavMeshPath  path  = new NavMeshPath();
        NavMeshAgent agent = (NavMeshAgent)instance;

        agent.enabled = false;
        Loom.QueueOnMainThread(delegate
        {
            SerializeNavMeshAgent.StoredInfo storedInfo = UnitySerializer.Deserialize <SerializeNavMeshAgent.StoredInfo>(data);
            agent.speed        = storedInfo.speed;
            agent.angularSpeed = storedInfo.angularSpeed;
            agent.height       = storedInfo.height;
            agent.baseOffset   = storedInfo.offset;
            agent.walkableMask = storedInfo.passable;
            if (storedInfo.hasPath && !agent.isOnOffMeshLink)
            {
                agent.enabled = true;
                if (NavMesh.CalculatePath(agent.transform.position, new Vector3(storedInfo.x, storedInfo.y, storedInfo.z), storedInfo.passable, path))
                {
                    agent.SetPath(path);
                }
            }
        }, 0.1f);
    }
Beispiel #25
0
 public object StartDeserializing(Entry entry)
 {
     this._reader.Read();
     if (this._reader.Token == JsonToken.ObjectStart)
     {
         this._reader.Read();
         if ((string)this._reader.Value == "___o")
         {
             this._reader.Read();
             JSONSerializer._isReference = true;
             JSONSerializer._reference   = (int)this._reader.Value;
         }
         else
         {
             JSONSerializer._isReference = false;
             JSONSerializer._reference   = -1;
             this._reader.Read();
             JSONSerializer._currentType = (string)this._reader.Value;
             entry.StoredType            = UnitySerializer.GetTypeEx(JSONSerializer._currentType);
         }
         return(null);
     }
     return(this._reader.Value);
 }
Beispiel #26
0
        private void EncodeType(object item, Type storedType)
        {
            if (item == null)
            {
                WriteSimpleValue((ushort)0xFFFE);
                return;
            }

            var itemType = item.GetType().TypeHandle;

            //If this isn't a simple type, then this might be a subclass so we need to
            //store the type
            if (storedType == null || storedType != item.GetType() || UnitySerializer.Verbose)
            {
                //Write the type identifier
                var tpId = UnitySerializer.GetTypeId(itemType);
                WriteSimpleValue(tpId);
            }
            else
            {
                //Write a dummy identifier
                WriteSimpleValue((ushort)0xFFFF);
            }
        }
Beispiel #27
0
 public object StartDeserializing(Entry entry)
 {
     _reader.Read();
     if (_reader.Token == JsonToken.ObjectStart)
     {
         _reader.Read();
         if ((string)_reader.Value == "___o")
         {
             _reader.Read();
             _isReference = true;
             _reference   = (int)_reader.Value;
         }
         else
         {
             _isReference = false;
             _reference   = -1;
             _reader.Read();
             _currentType     = (string)_reader.Value;
             entry.StoredType = UnitySerializer.GetTypeEx(_currentType);
         }
         return(null);
     }
     return(_reader.Value);
 }
Beispiel #28
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 #29
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 #30
0
 /// <summary>
 ///   Returns a <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" />.
 /// </summary>
 /// <returns> A <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" /> . </returns>
 public override string ToString()
 {
     return(Convert.ToBase64String(UnitySerializer.Serialize(this)));
 }
Beispiel #31
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="LevelSerializer.SaveEntry" /> class.
 /// </summary>
 /// <param name='contents'> The string representing the data of the saved game (use .ToString()) </param>
 public SaveEntry(string contents)
 {
     UnitySerializer.DeserializeInto(Convert.FromBase64String(contents), this);
 }
    /// <summary>
    /// The serialization required for playmaker integration. This is transparent for the user.
    /// 1: Add the "PlaymakerPhotonView" component to observe this fsm,
    /// 2: Add a "photonView" component to observe that "PlaymakerPhotonView" component
    /// 3: Check "network synch" in the Fsm variables you want to synch over the network, 
    /// 
    /// This setup is required For each Fsm. So if on one GameObject , several Fsm wants to sync variables, 
    /// you need a "PlaymakerPhotonView" and "PhotonView" setup for each.
    /// 
    /// TODO: this might very well need improvment or reconsideration. AT least some editor or runtime check and helpers.
    /// I am thinking of letting the user only add a "photonView" observing the fsm, and at runtime insert the "PlaymakerPhotonView" in between.
    /// But I can't run this check when an instanciation occurs as I have no notifications of this.
    /// 
    /// </summary>
    /// <param name='stream'>
    /// Stream of data
    /// </param>
    /// <param name='info'>
    /// Info.
    /// </param>
    void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.isWriting)
        {

            // go through the Look up table and send in order.
            foreach( PlayMakerPhotonFsmVariableDefinition varDef in variableLOT )
           		{

                switch (varDef.type)
                {
                    case PlayMakerPhotonVarTypes.Bool:
                        stream.SendNext(varDef.FsmBoolPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Int:
                        stream.SendNext(varDef.FsmIntPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Float:
                        stream.SendNext(varDef.FsmFloatPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.String:
                        stream.SendNext(varDef.FsmStringPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Vector2:
                        stream.SendNext(varDef.FsmVector2Pointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Vector3:
                        stream.SendNext(varDef.FsmVector3Pointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Quaternion:
                        stream.SendNext(varDef.FsmQuaternionPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Rect:
                        stream.SendNext(varDef.FsmRectPointer.Value);
                        break;
                    case PlayMakerPhotonVarTypes.Color:
                        UnitySerializer us = new UnitySerializer ();
                        us.Serialize(varDef.FsmColorPointer.Value);
                        stream.SendNext(us.ByteArray);
                        break;
                }
           		}

        }else{

            // go through the Look up table and read in order.
            foreach( PlayMakerPhotonFsmVariableDefinition varDef in variableLOT )
           		{
                switch (varDef.type)
                {
                    case PlayMakerPhotonVarTypes.Bool:
                        varDef.FsmBoolPointer.Value = (bool)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Int:
                        varDef.FsmIntPointer.Value = (int)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Float:
                        varDef.FsmFloatPointer.Value = (float)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.String:
                        varDef.FsmStringPointer.Value = (string)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Vector2:
                        varDef.FsmVector2Pointer.Value = (Vector2)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Vector3:
                        varDef.FsmVector3Pointer.Value = (Vector3)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Quaternion:
                        varDef.FsmQuaternionPointer.Value = (Quaternion)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Rect:
                        varDef.FsmRectPointer.Value = (Rect)stream.ReceiveNext();
                        break;
                    case PlayMakerPhotonVarTypes.Color:
                        UnitySerializer uds = new UnitySerializer ((byte[])stream.ReceiveNext());
                        varDef.FsmColorPointer.Value = uds.DeserializeColor();
                        break;
                }
           		}

        }// reading or writing
    }