Hi everyone. I made a simple script to save and load the remaining objects in my scene.
Since pickups shouldn’t return after leaving a scene.
The script works perfectly fine for me, for now, but i was wondering if there is a better way? I can imagine in a big level the loading time would be effected.
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace JohJong
{
public class JohJongScript : MonoBehaviour
{
[Header("Prefabs")]
[SerializeField] GameObject goldPrefap;
[SerializeField] public GameObject greenPotionPrefap;
private GameObject gameManager;
private GameObject[] allPickups;
public Pickups pickups = new Pickups();
private string appFile;
private string character;
private void Start()
{
// Find the GamaManager object
gameManager = GameObject.Find("GameManager");
// Set the current name of the player
character = gameManager.GetComponent<GameMenu>().current.currentCharacterName;
// Set the application save folder
appFile = Application.persistentDataPath;
}
public void SavePickups()
{
// Find all object tagged 'Pickup'
allPickups = GameObject.FindGameObjectsWithTag("Pickup");
// Clear the lists in class pickups
pickups.pickupsPosition.Clear();
pickups.pickupsNumber.Clear();
// Get all the positions and dedicated number
for (int i = 0; i < allPickups.Length; i++)
{
pickups.pickupsPosition.Add(allPickups[i].transform.position);
pickups.pickupsNumber.Add(allPickups[i].GetComponent<TokenScript>().number);
}
// Save to file
string pickupsData = JsonUtility.ToJson(pickups);
string pickupsFile = "Data_Level_1_Pickups.json";
string filePath = Path.Combine(appFile, character, pickupsFile);
System.IO.File.WriteAllText(filePath, pickupsData);
}
public void LoadPickups()
{
// Load the file
string pickupsFile = "Data_Level_1_Pickups.json";
string filePath = Path.Combine(appFile, character, pickupsFile);
string pickupsData = System.IO.File.ReadAllText(filePath);
// Clear the lists in class pickups
pickups.pickupsPosition.Clear();
pickups.pickupsNumber.Clear();
// Load data into the class pickups
pickups = JsonUtility.FromJson<Pickups>(pickupsData);
// Find all object tagged 'Pickup'
allPickups = GameObject.FindGameObjectsWithTag("Pickup");
// Destroy all objects tagged 'Pickup'
for (int i = 0; i < allPickups.Length; i++)
{
Destroy(allPickups[i]);
}
// Clear the array
allPickups = null;
// Create items according to dedicated number and position
for (int i = 0; i < pickups.pickupsPosition.Count; i++)
{
if (pickups.pickupsNumber[i] == 1)
{
Instantiate(goldPrefap, pickups.pickupsPosition[i], Quaternion.Euler(-90,0,0));
}
if (pickups.pickupsNumber[i] == 2)
{
Instantiate(greenPotionPrefap, pickups.pickupsPosition[i], Quaternion.Euler(0,0,0));
}
}
}
[System.Serializable] public class Pickups
{
public List<Vector3> pickupsPosition = new List<Vector3>();
public List<int> pickupsNumber = new List<int>();
}
}
}