1

i'm currently trying to save a n x m field array as json in a text file. I know unity doesn't support array types for top-level JSON deserialization. Therefore i have made a class which looks like this

public class Field{
    public int[][] id;
    public GameObject[][] gameObjectReference;
}

Wether the GameObject Array is stored in the json file isn't relevant but i still would like to save the id array. So far i have this code snipet to test this.

String[] aRows = System.IO.File.ReadAllLines(pathToSomeFile);       
field = new Field ();

    field.id = new int[aRows [0].Split(';').Length][];


    for (int i = 0; i < aRows [0].Split(';').Length; i++) {
        field.id [i] = new int[aRows.Length];
    }

    for (int y = 0; y < aRows.Length; y++) {
        for (int x = 0; x < aRows[y].Split(';').Length; x++) {
            field.id [x] [y] = int.Parse(aRows[y].Split(';')[x]);
        }   
    }

    GameManager.log (JsonUtility.ToJson (field));

But the console just says:

{}

The File im curretnly using looks something like this

5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5
5;5;5;5;5;5;5;5;5

What's wrong with my approach? pls help! i just cant figure it out.

1 Answer 1

1

From the documentation:

Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.

It sais that the supplied object (in your case the Field object) must be either a MonoBehaviour, ScriptableObject or a plain class (your case) with the Serializable attribute applied. You need to use the attribute.

So add the attribute to Field:

[Serializable]
public class Field{
    public int[][] id;
    public GameObject[][] gameObjectReference;
}

the int[][] is serializable and should make your code work, however I don't think the GameObject[][] is, and I'm not quite sure how we can get around that at the moment so it should be ignored. Anyway try your code with the tag first and let me know if it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.