Hi, I am developing a hobby farm game where a player is able to place crops and grow them and build up a farm etc. I am having difficulties in saving and then loading the GameObjects the player creates.
Right now parts of my approach to it is quite hacky. Each GameObject (Crop) being spawned has a Crop class, which stores a CropData ScriptableObject which stores all of it’s data. So far I have the saving of the objects position and loading that back in working fine. However, I’m unsure how to figure out how to save the ScriptableObject the GameObject references.
Currently I am using a String Reference and loading the ScriptableObject in from the Resources folder (Code Below). This seems very hacky however I can’t think of other ways to do it.
//Saving The Objects Data
private void OnDisable()
{
List<Transform> placedObjects = transform.GetComponentsInChildren<Transform>().ToList();
placedObjects.Remove(transform);
LevelData data = new LevelData();
foreach(Transform t in placedObjects)
{
if(t.GetComponent<BaseCrop>())
{
CropData cropData = new CropData();
cropData.transformData = new TransformData(t.localPosition.x, t.localPosition.y);
cropData.itemScriptableObject = t.GetComponent<BaseCrop>().CropData.fileName;
data.cropData.Add(cropData);
}
}
SaveSystem<LevelData>.SaveData(data, "LevelData");
}
//Data Class
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class LevelData
{
public List<CropData> cropData = new List<CropData>();
}
[Serializable]
public class CropData
{
public TransformData transformData = new TransformData(0,0);
public string itemScriptableObject = "";
}
[Serializable]
public class TransformData
{
public TransformData(float _x, float _y)
{
x = _x;
y = _y;
}
public float x;
public float y;
}
//Loading Data in
private void OnEnable()
{
LevelData data = SaveSystem<LevelData>.LoadData("LevelData");
if(data == null)
{
Debug.Log("Not found");
}
else
{
//Loop through for all Placeable Object Types, Crops and Buildings so far
foreach(CropData cropData in data.cropData)
{
Crop crop = (Crop)Resources.Load("Crops/" + cropData.itemScriptableObject);
Vector2 spawnLocation = new Vector2(cropData.transformData.x, cropData.transformData.y);
SpawnItem(crop, spawnLocation, Quaternion.identity);
}
}
}