- Home /
Serialize class with serializable fields,
Hello, I got a very specific question, and I haven't been able to find answer. I want to serialize my class, which contains serializable fields. Here's some code:
[Serializable]
public class House
{
[SerializeField]
public string Name;
[SerializeField]
public House Neighbor;
}
Update: (I wanted to narrow the question, but apparently did too much. Here's more details) I have script, which I call in editor, it assigns values to these fields, which I want to use at runtime. Name field persists when running the game, and I can use it, no problems. While Neighbor == null at runtime.
What do you expect neigbour should show I dont understand what you are trying here
@bartbussel, I updated the question with more info
Answer by Bunny83 · Jan 05, 2018 at 02:31 PM
"Normal" serializable classes are treated like structs by the serialization system. You can't have circular references in such a class since every reference to a "House" would be immediately instantiated by the inspector. This would result in an infinite chain of class instances.
The only references which Unity can actual serialize as references are references to other assets. More specifically classes derived from UnityEngine.Object. The classes you can use as base type are MonoBehaviour for custom components which are bound to a gameobject, or ScriptableObject which are standalone assets. Note that ScriptableObjects need to be stored as actual asset in the project.
See Script serialization for more information. Specifically the section "When might the serializer behave unexpectedly"
If I'm not mistaken, ScriptableObject instances can also be contained within a scene. It's something I experimented with once, but didn't actually end up using, because you can really only embed them in scenes and not within other Assets (e. g. within a prefab).
Your answer
Follow this Question
Related Questions
how to serialize unity variables? (Sprite, Image ...) 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is there a serialization class similar to JsonUtility but for Byte Serialization. 1 Answer
Object says it's null, but on inspecting it seems to have the correct value 1 Answer