Search Unity

Is it possible to serialize/save fields and properties in a custom editor?

Discussion in 'Scripting' started by TenderclawWill, Jul 12, 2018.

  1. TenderclawWill

    TenderclawWill

    Joined:
    Jun 14, 2018
    Posts:
    6
    Hey i am working on a custom editor for a unity created class (Mesh Renderer) and i have successfully made it so that the user can select an enum in the inspector and it will update the mesh renderer accordingly.

    This is all well and good, but whenever i deselect the object, the enum field in the editor script is reset to its default value (0) which is making me think its not serialized or saved anywhere. Ive searched for ways to save these values/get them to serialize, but have not found any useful info. Is this possible?

    If not, i'll likely just make a dictionary of game object IDs and the values that is updated on deselect, which should work but it feels like kind of a nuclear/slow solution to a simple problem.

    I cannot simply have it set a field in the class being edited (mesh renderer) because i can not (as far as im aware) inherit from or extend meshrenderer in any meaningful way.


    things ive tried to no success (will update this list as i keep trying things):
    marking the editor class as serializable
    marking the enum as serializable
    move the fields to a serialized class/struct and then use that in the editor script
    flagging the mentioned fields with [SerializeField]
    calling this.SetDirty() in the editor script
    calling EditorUtility.SetDirty(this) in the editor script


    Edit: looks like my idea of using a dictionary will not work either because gameobjectIDs dont seem to persist. Bummer
     
    Last edited: Jul 13, 2018
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    GameObjects will only save data that belongs to it's components, and components will only serialize the serializable data that is defined in their class. You cannot use an external class to "add" serialized data to an existing class, like MeshRenderer.

    I think the easiest way to do what you are doing is have your Editor script add a component to the same object as your MeshRenderer. The component should be a class that you create and has every serialized value you might want. When you want to access those values from the meshRenderer, you just call "meshRenderer.gameObject.GetComponent<MyComponent>().value".

    Just remember "GetComponent" can be slow, so you should probably cache the result so you only have to call it once. (I can explain this if you want)
     
    PlaxirStudio and ThermalFusion like this.