0

When I am trying to create a JSON using the below code it is showing a null exception error here.

myObject.test[0]="0";

myObject.test[1]="1";

myObject.test[2]="2";

How to fix this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JSON_Manager : MonoBehaviour
{
    public string JSON;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Node myObject = new Node();
        myObject.BrickName = "test";
        myObject.LED=false;
        myObject.test[0]="0"; //error
        myObject.test[1]="1";
        myObject.test[2]="2";
        string JSON = JsonUtility.ToJson(myObject);
        print(JSON);
    }
}

[System.Serializable]
public class Node
{
    public string BrickName;
    public bool LED;
    public string[] test;
    
}

1 Answer 1

2

This error happens since you are not initializing array. The initial capacity is 0, that is why it gives an error.

The easiest way to fix it is to write like that before accessing to the string or maybe create default constructor that will do it for you:

test = new string[size you need]
Sign up to request clarification or add additional context in comments.

1 Comment

In general rather use a List if you don't know the size beforehand ;) in json List<T> and T[] are completely exchangeable

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.