public virtual void JSOnSpawned() { if (Dbug.Is(DebugMode.INFO) && Debug) { print("Object " + name + " has been spawend at " + transform.position + "."); } }
public virtual void JSOnPooled() { if (Dbug.Is(DebugMode.INFO) && Debug) { print("Object " + name + " has been pooled."); } }
/// <summary> /// this method takes a savefile and a path and creates or overwrites an file at this path /// </summary> /// <param name="save">the content of the save</param> /// <param name="path">the path to save to</param> /// <returns>true if the saving was successfull, false if an error occured</returns> public bool SaveFile(Save save, string path) { try { BinaryFormatter myBinaryFormatter = new BinaryFormatter(); FileStream myFileStream = File.Create(path); if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Saved to " + path); } myBinaryFormatter.Serialize(myFileStream, save); myFileStream.Close(); return(true); } catch (System.Exception myException) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Some error occured: " + myException.Message + path + ". Returning false."); } return(false); throw; } }
public virtual void JSOnDespawned() { if (Dbug.Is(DebugMode.INFO) && Debug) { print("Object " + name + " has been despawend. Returning to pool."); } }
GameObject Spawn(PoolObjectInformation PoolEntry, GameObject PrefabToSpawn, List <ISavable> SavablesInObject, Vector3 Position) { if (Dbug.Is(DebugMode.EXTENSIVE)) { Debug.Log("Spawning Object " + PoolEntry.ObjectReference.GetComponent <JustSaveRuntimeId>().GetSaveIdentifier()); } PrefabToSpawn.GetComponent <JustSaveRuntimeId>().Spawn(); PrefabToSpawn.transform.position = Position; PrefabToSpawn.SetActive(true); Pool.Add(PoolEntry); Pool.RemoveAt(0); //calling JSOnSpawned() on every Savable in the Prefab foreach (Savable mySavable in SavablesInObject) { mySavable.JSOnSpawned(); } if (NotifyToDespawn > 0 && GetPoolSize() - CurrentlyActiveObjects <= NotifyToDespawn) { foreach (ISavable ISavableComponent in Pool[NotifyToDespawn].SavablesInObject) { ISavableComponent.JSOnNeeded(); } } CurrentlyActiveObjects++; return(PrefabToSpawn); }
public virtual void JSOnNeeded() { if (Dbug.Is(DebugMode.INFO) && Debug) { print("Calling " + name + " to despawn itself."); } }
/// <summary> /// Spawning an object with object pooling. If all pools with the given Id are empty, returns false. /// </summary> /// <param name="PrefabId">The Id of the prefab to be spawned. Id should match the Id of some object pool.</param> /// <param name="Position">The position at which the prefab shall be spawned</param> /// <returns>True if an object was spawned. False if no object was spawned</returns> public GameObject Spawn(string PrefabId, Vector3 Position) { if (PrefabId == null || Position == null) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogWarning("Spawning was called on ObjectPoolingManager with Null-Pointer arguments."); } return(null); } foreach (PoolKey myPoolKey in ObjectPoolingList) { if (myPoolKey.key.Equals(PrefabId)) { return(myPoolKey.pool.Spawn(Position)); } } if (Dbug.Is(DebugMode.ERROR)) { Debug.LogWarning("The ObjectPoolingManager found no ObjectPool corresponding to the id: " + PrefabId); Debug.LogWarning("List of all registered ObjectPools:"); foreach (PoolKey myPoolKey in ObjectPoolingList) { Debug.LogWarning(myPoolKey.key); } } return(null); }
public void ResetSavePath() { path = Application.persistentDataPath + System.IO.Path.DirectorySeparatorChar; if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Reset savepath. Complete path is now: " + path + fileName + fileEnding); } }
public Quaternion GetQuaternion() { if (fields.Length < 4) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("JSNTuple has not enough fields to support Quaternion. Returning identity."); } return(Quaternion.identity); } return(new Quaternion(fields[0], fields[1], fields[2], fields[3])); }
public Vector4 GetVector4() { if (fields.Length < 4) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("JSNTuple has not enough fields to support Vector4. Returning default vector (0,0,0,0)."); } return(new Vector4(0, 0, 0, 0)); } return(new Vector4(fields[0], fields[1], fields[2], fields[3])); }
/// <summary> /// Despawns a Savable Object by given PoolObjectInformation /// </summary> /// <param name="PoolObject">The poolentry to use for despawning</param> public void Despawn(PoolObjectInformation PoolObject) { if (Dbug.Is(DebugMode.EXTENSIVE)) { Debug.Log("Despawning Object " + PoolObject.ObjectReference.GetComponent <JustSaveRuntimeId>().GetSaveIdentifier()); } PoolObject.ObjectReference.SetActive(false); PoolObject.SetSpawned(false); PoolObject.ObjectReference.transform.position = Vector3.zero; CurrentlyActiveObjects--; }
/// <summary> /// call this method to save everything. Automatically assembles a save file and saves it. /// </summary> public void Save() { if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Saving..."); } Save newSave = mySaveAssembler.GetCurrentSave(); if (myFileManager.SaveFile(newSave, path + fileName + fileEnding) && Dbug.Is(DebugMode.INFO)) { Debug.Log("File saved successfully"); } }
/// <summary> /// Sets the NotifyToDespawn-value /// </summary> /// <param name="NotifyToDespawn">when an object in the pool is *n* objects away from beeing reused, it will be notified</param> public void SetNotifyToDespawn(int NotifyToDespawn) { if (GetPoolSize() < NotifyToDespawn) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Cant Set NotifyToDespawn to " + NotifyToDespawn + ", because the pool only has " + GetPoolSize() + " members."); } } else { this.NotifyToDespawn = NotifyToDespawn; } }
public void SetFileName(string newFileName) { if (newFileName != "" && newFileName != null) { fileName = newFileName; if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Filename set to " + newFileName + ". Complete path is now: " + path + fileName + fileEnding); } } else if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Filename can not be empty or null."); } }
public void SetFileEnding(string newFileEnding) { if (newFileEnding != null) { fileEnding = newFileEnding; if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Fileending set to " + newFileEnding + ". Complete path is now: " + path + fileName + fileEnding); } } else if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Fileending can not be null."); } }
public void SetFilePath(string newFilePath) { if (newFilePath != null && newFilePath != "") { path = newFilePath; if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Filepath set to " + newFilePath + ". Complete path is now: " + path + fileName + fileEnding); } } else if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Filepath can not be null or empty."); } }
/// <summary> /// getting a value from the given savefile from the given path /// </summary> /// <param name="save">The save to get the value from</param> /// <param name="Runtime">True if the following Id is runtime, false if it is a scene id</param> /// <param name="ObjectIdentifier">The Id of the object to find</param> /// <param name="ComponentIdentifier">The Identifier of the Component from which this field will be saved</param> /// <param name="FieldName">The Name of the Field from which the value was extracted</param> /// <param name="Value">The Value to save. Must derive from JSSerializable</param> public JSSerializable GetValue(Save save, bool Runtime, string ObjectIdentifier, string ComponentIdentifier, string FieldName) { JSSerializable result = null; result = ((JSDictionary <JSSerializable>)((JSDictionary <JSSerializable>)save.GetByKey(Runtime ? "Runtime" : "Static") .GetValueByKey(ObjectIdentifier)).GetValueByKey(ComponentIdentifier)).GetValueByKey(FieldName); if (result == null) { if (Dbug.Is(DebugMode.WARN)) { Debug.LogWarning("There was a problem getting a value for the Autosave field at: " + ObjectIdentifier + " " + ComponentIdentifier + " " + FieldName); } } return(result); }
/// <summary> /// call this method to load everything. /// </summary> public void Load() { if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Loading..."); } Save loadedSave = myFileManager.LoadFile(path + fileName + fileEnding); if (Dbug.Is(DebugMode.DEBUG)) { Debug.Log("Save to load: " + loadedSave.ToString()); Debug.Log("Shortform: " + loadedSave.ToShortString()); } mySaveInterpreter.InterpretSave(loadedSave); if (Dbug.Is(DebugMode.INFO)) { Debug.Log("File loaded."); } }
public GameObject Spawn(Vector3 Position) { //Force Spawning will always find an target if (Mode == PoolingMode.ForceDespawn) { return(Spawn(Pool[0], Pool[0].ObjectReference, Pool[0].SavablesInObject, Position)); } else if (Mode == PoolingMode.ReturnNull) { if (GetPoolSize() > CurrentlyActiveObjects) { return(Spawn(Pool[0], Pool[0].ObjectReference, Pool[0].SavablesInObject, Position)); } else { if (Dbug.Is(DebugMode.INFO)) { Debug.LogWarning("Object Pool for " + SpawnPrefabId + " empty. (" + CurrentlyActiveObjects + " objects spawned). Cannot spawn object. Returning null."); } return(null); } } else if (Mode == PoolingMode.OnDemand) { if (GetPoolSize() > CurrentlyActiveObjects) { return(Spawn(Pool[0], Pool[0].ObjectReference, Pool[0].SavablesInObject, Position)); } else { BasePoolSize++; FillPool(true); if (Dbug.Is(DebugMode.INFO)) { Debug.LogWarning("Adding new Object to Pool for " + SpawnPrefabId + ". Spawning new object. New pool size: " + GetPoolSize()); } return(Spawn(Pool[0], Pool[0].ObjectReference, Pool[0].SavablesInObject, Position)); } } return(null); }
/// <summary> /// tries to get the value associated with a key. If no value was found, returns null /// </summary> /// <param name="key">the key associated with the wanted value</param> /// <returns>value of type T or null, if the key is no associated with any value</returns> public T GetValueByKey(string key) { if (savedValues.ContainsKey(key)) { return(savedValues[key]); } else { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("key " + key + " not found"); Debug.LogError("Available keys would be: "); foreach (string debug_key in savedValues.Keys) { Debug.LogError(debug_key); } } return(null); } }
public string ToShortString() { string result = ""; result = result + " " + (savedValues.Keys.Count > 6 ? savedValues.Count + ":" : ""); foreach (String key in savedValues.Keys) { try { result = result + (key.Length <= 20 ? key.Split('_')[0].Replace("JustSave", "") : key.Substring(0, 20).Split('_')[0]).Replace("JustSave", "") + ((GetValueByKey(key) is JSDictionary <JSSerializable>) ? "(" + (GetValueByKey(key) as JSDictionary <JSSerializable>).ToShortString() + ") " : "") + " "; } catch (Exception) { if (Dbug.Is(DebugMode.WARN)) { Debug.LogError("An error occured while getting value to key: " + key + ". Could Therefore not print JSDictionary to console."); } throw; } } return(result); }
/// <summary> /// Creates the dictionary as a string representation /// </summary> /// <returns>a string representation of the dictionary</returns> public override string ToString() { string result = ""; result = result + "Count: " + savedValues.Keys.Count + " "; foreach (String key in savedValues.Keys) { try { result = result + key + ": " + GetValueByKey(key).ToString() + "; "; } catch (Exception) { if (Dbug.Is(DebugMode.WARN)) { Debug.LogError("An error occured while getting value to key: " + key + ". Could Therefore not print JSDictionary to console."); } throw; } } return(result); }
/// <summary> /// this method takes the path to a savefile, loads the file from this path (if it exists) and returns it, deserialized /// </summary> /// <param name="path">the path under which a savefile should be found</param> /// <returns>the found savefile. returns null, if no savefile was found</returns> public Save LoadFile(string path) { if (File.Exists(path)) { try { if (Dbug.Is(DebugMode.INFO)) { Debug.Log("Reading file at " + path); } BinaryFormatter myBinaryFormatter = new BinaryFormatter(); FileStream myFileStream = File.Open(path, FileMode.Open); Save mySave = (Save)myBinaryFormatter.Deserialize(myFileStream); myFileStream.Close(); return(mySave); } catch (System.Exception) { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("Some error occured while loading file at " + path + ". Returning null pointer."); } return(null); throw; } } else { if (Dbug.Is(DebugMode.ERROR)) { Debug.LogError("No file found at " + path + "."); } return(null); } }
/// <summary> /// assembles a new JustSave.Save from the current application and returns this Save. /// </summary> /// <returns>the assembled Save</returns> /// public Save GetCurrentSave() { Save newSave = new Save(); int OverwriteCounter = 0; //use this dictionary to remember once scanned classes for later use Dictionary <Type, FieldInfo[]> RememberedFields = new Dictionary <Type, FieldInfo[]>(); //getting references to spawning and autosaves JSDictionary <JSSerializable> Runtime = newSave.Runtime; JSDictionary <JSSerializable> Static = newSave.Static; JustSaveId[] JSManagedObjects = UnityEngine.Object.FindObjectsOfType <JustSaveId>(); bool IsRuntime; foreach (JustSaveId IdObj in JSManagedObjects) { //its either a JustSaveRuntime Id if (IdObj is JustSaveRuntimeId) { IsRuntime = true; } //or a SceneId else { IsRuntime = false; } GameObject Search = IdObj.gameObject; Component[] Components = Search.GetComponentsInChildren <Component>(); List <Attribute> Attributes = new List <Attribute>(); FieldInfo[] FieldInfos; //getting the attributes foreach (Component m_Comp in Components) { //calling JSOnSave on every class implementing the ISavable interface if (m_Comp is ISavable) { ((ISavable)m_Comp).JSOnSave(); } if (!RememberedFields.TryGetValue(m_Comp.GetType(), out FieldInfos)) { FieldInfos = m_Comp.GetType().GetFields(); RememberedFields.Add(m_Comp.GetType(), FieldInfos); } foreach (FieldInfo Field in FieldInfos) { if (Attribute.IsDefined(Field, typeof(Autosaved))) { Type AutosaveFieldType = Field.FieldType; // already serializable Types if (AutosaveFieldType.IsSerializable) { if (!(SaveValue(newSave, IsRuntime, IdObj.GetSaveIdentifier(), m_Comp.GetType().Name, Field.Name, JSBasic.GetFromObject(Field.GetValue(m_Comp))))) { OverwriteCounter++; } } // support for unitys vector-types else if (AutosaveFieldType == typeof(Vector2)) { if (!(SaveValue(newSave, IsRuntime, IdObj.GetSaveIdentifier(), m_Comp.GetType().Name, Field.Name, JSNTuple.GetFromVector2((Vector2)Field.GetValue(m_Comp))))) { OverwriteCounter++; } } else if (AutosaveFieldType == typeof(Vector3)) { if (!(SaveValue(newSave, IsRuntime, IdObj.GetSaveIdentifier(), m_Comp.GetType().Name, Field.Name, JSNTuple.GetFromVector3((Vector3)Field.GetValue(m_Comp))))) { OverwriteCounter++; } } else if (AutosaveFieldType == typeof(Vector4)) { if (!(SaveValue(newSave, IsRuntime, IdObj.GetSaveIdentifier(), m_Comp.GetType().Name, Field.Name, JSNTuple.GetFromVector4((Vector4)Field.GetValue(m_Comp))))) { OverwriteCounter++; } } else if (AutosaveFieldType == typeof(Quaternion)) { if (!(SaveValue(newSave, IsRuntime, IdObj.GetSaveIdentifier(), m_Comp.GetType().Name, Field.Name, JSNTuple.GetFromQuaternion((Quaternion)Field.GetValue(m_Comp))))) { OverwriteCounter++; } } // no support else { if (Dbug.Is(DebugMode.WARN)) { Debug.LogWarning("Field " + Field.Name + " of Type " + AutosaveFieldType.Name + " is not serializable and will be skipped."); } } } } } } if (Dbug.Is(DebugMode.DEBUG)) { Debug.Log("______Assembled Save______"); Debug.Log(newSave.ToString()); Debug.Log("__________________________"); Debug.Log("______Short Form Save______"); Debug.Log(newSave.ToShortString()); Debug.Log("__________________________"); Debug.Log("Scanned a total of " + RememberedFields.Keys.Count + " different classes."); Debug.Log("Overwritten: " + OverwriteCounter + " Fields. Perfect!"); } if (OverwriteCounter > 0 && Dbug.Is(DebugMode.WARN)) { Debug.LogWarning("Overwritten: " + OverwriteCounter + " Fields. You should look into this."); } return(newSave); }
/// <summary> /// Interprets a given save and applies the data to the Application /// </summary> /// <param name="source">The save to interpret</param> /// <returns>True if the method reached the end of the calculation without fatal errors</returns> public bool InterpretSave(Save source) { List <int> arrayList = new List <int>(); //getting references to spawning and autosaves JSDictionary <JSSerializable> Runtime = source.Runtime; JSDictionary <JSSerializable> Static = source.Static; //use this dictionary to remember once scanned classes for later use Dictionary <Type, FieldInfo[]> RememberedFields = new Dictionary <Type, FieldInfo[]>(); //preparing references and despawning runtime objects JustSaveId[] JSManagedObjects = UnityEngine.Object.FindObjectsOfType <JustSaveId>(); List <JustSaveSceneId> JSManagedSceneObjects = new List <JustSaveSceneId>(); foreach (JustSaveId JustSaveManagedObject in JSManagedObjects) { if (JustSaveManagedObject is JustSaveRuntimeId) { ((JustSaveRuntimeId)JustSaveManagedObject).Despawn(); //despawns every runtime object } else { JSManagedSceneObjects.Add((JustSaveSceneId)JustSaveManagedObject); //saves every scene object reference } } if (Dbug.Is(DebugMode.DEBUG)) { Debug.Log("Save Interpreter despawned old runtime objects"); } //loading scene objects foreach (JustSaveSceneId IdObj in JSManagedSceneObjects) { SyncObject(source, false, IdObj, RememberedFields); } if (Dbug.Is(DebugMode.DEBUG)) { Debug.Log("Save Interpreter synced scene objects"); } //iterating through spawned objects string[] idInfo = new string[2]; foreach (Tuple <String, JSSerializable> RuntimeObjectInfo in Runtime.GetValuePairs()) { idInfo = RuntimeObjectInfo.Item1.Split('_'); GameObject spawnedPrefab = JustSaveManager.Instance.Spawn(idInfo[0], Vector3.zero); JustSaveRuntimeId spawnedIdObj = spawnedPrefab.GetComponent <JustSaveRuntimeId>(); spawnedIdObj.SetId(Guid.Parse(idInfo[1])); SyncObject(source, true, spawnedPrefab.GetComponent <JustSaveRuntimeId>(), RememberedFields); } if (Dbug.Is(DebugMode.DEBUG)) { Debug.Log("Save Interpreter spawned and synced runtime objects"); Debug.Log("Save Interpreter finished loading Save"); } return(true); }