Scriptable Objects reset after any type of Reload. What am i doing wrong?

Hello, Can anyone help me with scriptable objects?

So, I’m trying to make an editor script for the scriptable object so that it shows toggle buttons and I can store where obstacles need to be instantiated on the grid. But, currently what happens is when I hit play or restart unity or recompile scripts the scriptable object gets reset.

Below are the relevant scripts:

Obstacle Editor:

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(ObstacleData))]
public class ObstacleEditor : Editor
{
    public override void OnInspectorGUI()
    {
        ObstacleData obstacleData = (ObstacleData)target;

        for (int row = 0; row < 10; row++)
        {
            EditorGUILayout.BeginHorizontal();
            for (int col = 0; col < 10; col++)
            {
                obstacleData.blockedTiles[row,col] = EditorGUILayout.Toggle(obstacleData.blockedTiles[row,col]);
              
            }
            EditorGUILayout.EndHorizontal();
        }

        if(GUI.changed)
        {
            EditorUtility.SetDirty(obstacleData);
        }
    }
}

ObstacleData:

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


[CreateAssetMenu(fileName = "ObstacleData", menuName = "ScriptableObjects/Obstacle Data")]
public class ObstacleData : ScriptableObject
{
    [SerializeField] public bool[,] blockedTiles = new bool[10,10];
}

You are modifying the target directly. Instead you are supposed to modify the SerializedObject or SerializedProperty field of the target object - otherwise any changes to the target object will be lost because target is a transient instance of your SO.

There’s a quick fix if you follow up this line with:
AssetDatabase.SaveAssetIfDirty(obstacleData);

I’m not 100% sure whether this will work but I’ve seen it being used. The problem with that hack is that you forfeit the undo/redo mechanism.

Last I checked Unity doesn’t support serializing 2D arrays. Perhaps this has changed?

@spiney199 is our resident serialization expert here. :slight_smile:

Yes Unity does not support serialisation of multi-dimensional, jagged etc arrays. You can read all about what Unity can and can’t serialise here: Unity - Manual: Script serialization

Writing a custom inspector or property drawer to draw these values doesn’t change what Unity can and can’t serialise. If you want to serialise something Unity can’t, your options are to:

  • Use the ISerializationCallbackReciever to to translate the data to a form Unity can serialise and back again
  • Reconfigure your data layout to be inherently serialisable by Unity
  • Use an addon like Odin Inspector & Serializer which can both serialise and draw multi-dimensional arrays.