Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Help with custom inspector serialization.

Discussion in 'Scripting' started by webcam, Apr 22, 2018.

  1. webcam

    webcam

    Joined:
    May 1, 2017
    Posts:
    2
    I would usually post this to answers but there is some bug right now that automatically logs me out when I open answers that is preventing me from posting.

    I am trying to create a simple state machine with a custom inspector that allows me to easily add, remove and edit states. Adding states isn't serializing properly so when the project compiles all added data is removed. So if I run addState 3 times it will show 3 states in the dictionary but as soon as the project compiles it goes back to being empty.

    This is the logic in my custom inspector to add a state.

    private void addState(string stateName)
    {
    Undo.RegisterCompleteObjectUndo(_target, "Added New State");
    stateName = stateName + _target.states.Count;
    State newState = new State(stateName);
    _target.states[stateName] = newState;
    }

    This is my state class.

    [System.Serializable]
    public class State
    {
    [SerializeField]
    string _name;

    public State(string name)
    {
    _name = name;
    }
    }


    Please help this problem is killing me.
     
  2. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    Dictionaries usually have problem with serialization, so it could be that your dictionary doesn't serialize values on reload. You could use an alternative approach like another collection (List<State>) just for serialization and then convert it to dictionary in the Awake() method of your component. Or, make your component implement ISerializationCallbackReceiver, just like in Unity docs:

    https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html

    good thing is, there are numerous ways to approach this problem. Making a custom collection that is reusable and serializable might be the best approach longterm.
     
  3. webcam

    webcam

    Joined:
    May 1, 2017
    Posts:
    2
    I did end up giving up on using a dictionary for this reason. Implemented it with a list and it's much easier to work with now.