/// <summary> /// Saves the bombs. /// </summary> public void SaveBombs() { // Setup the data to be saved. string[] bombNames = new string[typesOfBombs.Length]; int[] bombAmount = new int[typesOfBombs.Length]; // Loop the amount of times we have bombs. for (int i = 0; i < typesOfBombs.Length; i++) { bombNames [i] = typesOfBombs [i].bombObject.name; bombAmount [i] = typesOfBombs [i].bombAmount; } // Create a new Bomb_Data for our information to be saved. Bomb_Data data = new Bomb_Data(); data.bombName = bombNames; data.bombAmount = bombAmount; // Create a new data structure for our saving. Bomb_Choice choiceData = new Bomb_Choice(); // Save the data. choiceData.bombChoice = bombChoice; // Turn the data into Json data. string bombToJson = JsonUtility.ToJson(data); string bombChoiceToJson = JsonUtility.ToJson(choiceData); // Save this information. PlayerPrefs.SetString("Bombs", bombToJson); PlayerPrefs.SetString("BombsChoice", bombChoiceToJson); }
/// <summary> /// Loads the bombs. /// </summary> private void LoadBombs() { // Get the saved information. string bombJson = PlayerPrefs.GetString("Bombs"); string bombChoiceJson = PlayerPrefs.GetString("BombsChoice"); // IF we have a null or empty string. if (String.IsNullOrEmpty(bombJson)) { // We do nothing. return; } // Cast the Json data to our Bomb information. Bomb_Data data = JsonUtility.FromJson <Bomb_Data> (bombJson); Bomb_Choice choiceData = JsonUtility.FromJson <Bomb_Choice> (bombChoiceJson); // Since we are loading we need to do a compare with the name and associate the amount that way, as when you are developing there are times you forget things when you were planning everything out, so this will take care of // implementations you shall add in the future without giving any errors instead of flat out just matching the amounts with the array index integer. // We only want to fully loop the length of what was saved. for (int i = 0; i < data.bombName.Length; i++) { // Lets grab the name of our entry to compare to the main list that is in the inspector. string name = data.bombName [i]; for (int j = 0; j < typesOfBombs.Length; j++) { // IF the name in our saved data matches the name of the GameObject for the Bombs.cs script in in your Inspector. if (name == typesOfBombs [j].bombObject.name) { // We set the amount. typesOfBombs [j].bombAmount = data.bombAmount [i]; } } } // Set the bomb we currently have. bombChoice = choiceData.bombChoice; }