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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

ScriptableObject Not Keeping Data Between Scenes

Discussion in 'Scripting' started by Nigey, Dec 15, 2021.

  1. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Hi Guys,

    I created a ScriptableObject object using CreateAssetMenu. I only have one object created in the Project.

    I want to use it to store data between scenes. In the SO I have two Serialized classes, where I want to set the data in one scene. Then in later scenes reference the same SO and get the data. However what I'm finding is that in the first scene it'll set the data. Then on the next scenes load it will not keep the data, even though it's been Serialized. As I understand it SO keep Serialized data between scenes, both in play mode and edit mode? Struggling to understand the behaviour!

    Here's the top of the class for some reference:

    Code (CSharp):
    1.     [CreateAssetMenu(fileName = "Session", menuName = "Company/Session", order = 1)]
    2.     public class Session : ScriptableObject
    3.     {
    4.         private const float TimeoutIncrement = 0.1f;
    5.        
    6.         #if UNITY_EDITOR
    7.         [SerializeField, Tooltip("Only exists for editor sessions.")] private EditorAuthenticationService editorServiceConnection;
    8.         #endif
    9.        
    10.         [SerializeField] private string rootUrl;
    11.         [SerializeField] private float connectionTimeout = 5f;
    12.         [SerializeField] private UserContext userContext;
    13.         [SerializeField] private User user;
    14.         [SerializeField, ReadOnly] private bool connected;
    15.        
    Any help would to understand why it's not keeping the data would be greatly appreciated!

    I'm logging to affirm the data using this:


    Code (CSharp):
    1.         private void OnEnable()
    2.         {
    3.             Debug.Log("ENABLE:" + JsonUtility.ToJson(userContext));
    4.         }
    5.  
    6.         private void OnDisable()
    7.         {
    8.             Debug.Log("DISABLE:" + JsonUtility.ToJson(userContext));
    9.         }
    As OnEnable and OnDisable still activate when they're referenced by a GameObject's component in an active scene.
     
  2. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    Do you create an instance of it and manipulate that or are you modifying the asset directly?
     
  3. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129