S
S
Sergey Bezrukov2019-01-31 18:59:39
C++ / C#
Sergey Bezrukov, 2019-01-31 18:59:39

Why does this code have such a result?

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

public class test : MonoBehaviour {

  public Save sv;

  public void Awake()
  {
    sv = JsonUtility.FromJson<Save>(PlayerPrefs.GetString("SV"));
    Debug.Log(sv.test.Length);
    Debug.Log("Begin - " + sv.achieveStatus.Length);		
  }
  public void OnApplicationQuit()
  {		
    Debug.Log(sv.test.Length);
    Debug.Log("End - " + sv.achieveStatus.Length);
    PlayerPrefs.SetString("SV", JsonUtility.ToJson(sv));
    PlayerPrefs.Save();
  }
}

[System.Serializable]
public class Save
{
  public byte[] test;
  public byte[,] achieveStatus;
}

this code throws an error: object reference not set to an instance of an object
After that, I initialized the arrays and it turned out like this:
public byte[] test = new byte[3];
public byte[,] achieveStatus = new byte[3,3];

On startup and on exit, the code outputs 3 and 9 to the console. But then, when I removed new byte[3] and new byte[3,3] . And I ran 3 in the console and object reference not set to an instance of an object and the same thing happens when I exit. That is, in the player prefs, the one-dimensional array is preserved, but the two-dimensional one, it turns out that it is not. Why is that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Gaydak, 2019-01-31
@Hrederik

not "not saved".
and the Json serializer does not know how to work with multidimensional arrays.
replace it with something in the spirit of .. an array of arrays or a list of lists))
this can be serialized, and access to the same indexes will remain.

V
VoidVolker, 2019-01-31
@VoidVolker

For JSON in C#, there is an excellent class generation service and library: Newtonsoft.Json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question