Saving data from multiple game objects

I am creating a farming game and can’t figure out how to save the plots and plants data across different scenes. I’ve tried to save the data to a scriptable object, but that isn’t working out too well. I’m stuck.

I have a gameSaveManager singleton that just holds a List of Scriptable Objects (for example my inventory), and if possible would like to save the farming objects the same way. Currently the way the farming works is the player can click to create a plot object which should have its own attributes like watered or daysUntouched so that it can turn back to grass. Then the player can plant some seeds there and I have scriptable objects for all the plant data. What would be the best way to approach saving the information for each plot and associated plant?

JSON JSON JSON.

Let mew explain, say you have a plot of land.

public class LandPlot : MonoBehaviour {
	public List<Plant> listOfPlants;
}

Now what you will need to do is create an additional JsonData or SaveData class that can be used to save the data.
The data class must be the same one for all the objects of type Plant. Meaning if we have something like:

public class Tree : Plant {}
public class Bush : Plant {}

Won’t work! Why you ask? The issue is not in the saving, it actualyl saved fine. But when you load the data you will have issue when using JSON and Inheritance.
So make sure your data class has enough information to save everything associated with your objects so you can load it later on. But first how do we save it???

Simple:

public void SaveAsJson (object obj, string path){

	// Convert to Json
	string json = JsonUtility.ToJson(obj);
	
	//write string to file
	System.IO.File.WriteAllText(path, json);
}

Easy right? Well now we gotta recall it:

public T LoadObject<T> (path){
	json readText = File.ReadAllText(path);
	return JsonUtility.FromJson<T>(json);
}

Usage Example:

public List<Plant> listOfPlants;

public void SaveJsonTest () {
	print(SaveAsJson(listOfPlants, "C://SaveData/MyGame/SaveGame1.txt"));
}

public void LoadJsonTest () {
	print(LoadObject<List<Plant>>("C://SaveData/MyGame/SaveGame1.txt"));
}

And its easy as that. You can make it more robust by directly saving as a Json file. But code for that is more complicated (not by much).

But now you want to save MULTIPLE PLOTS? You crazy… but the concept remains the same:

// Lists of Lists of Plants are essentially mutlople plants
public List<List<Plant>> listOfPlants;

public void SaveJsonTest () {
	print(SaveAsJson(listOfPlants, "C://SaveData/MyGame/SaveGame1.txt"));
}

public void LoadJsonTest () {
	// Note how the Type for this changed to reflect ListOfPlants
	print(LoadObject<List<List<Plant>>>("C://SaveData/MyGame/SaveGame1.txt"));
}

with that you can stack all the objects in your game into a single file, or save them into seperate files that looks nicer