Serialize serialized Classes as reference in to the same class in the class - serialization loop problem

So - I have a loop Problem and I don’t know how to solve it.
I have a list of Objects and the have to reference to other objects of the same class.
The game logic is that a bed won’t work without a wardrobe, or a machine wouldn’t work if there is no energy generator.

The code looks like this:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

[System.Serializable]
public class RoomObject {

    public GameObject theObject;
//there is the serialization loop
    public List<RoomObject> requiredObjects = new List<RoomObject>();
    public string nameOfObject;
    public string descriptionOfObject;
    public Sprite logoOfObject;
}

how to solve that problem?
I don’t want to reference strings as they could change
and if there were enums, I’d need plenty of them.

also I tried adding
[System.NonSerialized]
which causes that these Variables/References are not saved - when I click “Play” in Unity, all those Objects are gone and the List of “requiredObjects” is empty
thanks in advance

2 Answers

2

Is there a reason that RoomObject needs to inherit from System.Object? Given that RoomObject contains a reference to a GameObject and a name, why is it not just a Component? For example:

using UnityEngine;
using System.Collections.Generic;

public class RoomObject : MonoBehaviour {
    [SerializeField]
    private string m_Description = "";
    [SerializeField]
    private Sprite m_Logo = null;
    [SerializeField]
    private List<RoomObject> m_RequiredObjects = new List<RoomObject> ();
}

This lets you also define prefabs for your RoomObjects, instead of potentially having to create duplicate information all over the place.

I guess it's needed because it's our data system - inherting from a Singleton, so I can't use monobehaviours, or it won't initialise them. But if classes have IDs or something, I may could use those to avoid the loop, and save the ID of the reference class. But I couldn't find any more helpful information to that topic.

I just woke up, so forgive me if I dont understand this correctly but of I understand the comments…

  1. Your simulation (data) is separate from Unity, so it cant be a monobehavior

  2. This script holds both Simulation (data) and Unity (reference to gameobject).

What you’d want to do is separate the two entirely.

This script should inherit from monobehavior, and either reference the simulation or store copies of the variables from the simulation.

I wrote in length about this here. Does this answer your question?

I’m not exactly sure what the problem is in the question. Of you want to have some random ID to reference objects, you could simply give every object a unique GUID. Strings & Enums are awesome, so I’m not understanding why you wouldnt want to use them…well, or what youre even needing them for.