I have a class GameObject
with a public List<Component> Components
. I am using Json.NET to store a list of GameObjects that are kept as a list inside a Scene
class, so that I can load them in later.
Component
is an abstract class. I want to be able to load all of my Components
. The loading/saving system I have right now is simple.
Loading the scene:
string Text = File.ReadAllText(Path);
Scene CurrentScene = JsonConvert.DeserializeObject<Scene>(Text);
Saving it:
string JSON = JsonConvert.SerializeObject(Scene, Formatting.Indented, SerializerSettings);
File.WriteAllText(Path, JSON);
Whenever I try to load the scene and I try to access a component, I get a 'NullReferenceException` error.
Edit:
public static Scene LoadScene(string Path)
{
if (!File.Exists(Path))
{
Debug.LogError("There is no scene file with the specified path!");
return new Scene();
}
string Text = File.ReadAllText(Path);
Scene CurrentScene = JsonConvert.DeserializeObject<Scene>(Text);
foreach (GameObject GObject in CurrentScene.gameObjects)
for(int i = 0; i <= GObject.Components.Count - 1; ++i)
GObject.Components[i] = JsonConvert.DeserializeObject<Component>(Text, new ComponentConverter());
return CurrentScene;
}
public static void CreateSceneFile(string Path, Scene Scene, bool Overwrite)
{
if(File.Exists(Path) && !Overwrite)
{
Debug.LogError("There already exists a scene file with the specified path!");
return;
}
JsonSerializerSettings SerializerSettings = new JsonSerializerSettings();
SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
string JSON = JsonConvert.SerializeObject(Scene, Formatting.Indented, SerializerSettings);
File.WriteAllText(Path, JSON);
}
[Serializable]
public class Scene
{
public List<GameObject> gameObjects = new List<GameObject>();
}
[Serializable]
public class GameObject
{
public List<Component> Components = new List<Component>();
public Transform transform = new Transform(); // Separate so that it can't be removed
public Scene scene // Scene it belongs to
public string name = "GameObject";
public string tag = "Untagged";
}
[Serializable]
public class Component
{
public virtual void FixedUpdate() { }
public virtual void LateUpdate() { }
public virtual void Update() { }
public virtual void Start() { }
public virtual void Close() { }
public GameObject gameObject;
public string name; // added just to see the name in the json
}
Still haven't found a suitable solution