Savad
Savad

Reputation: 1316

Unity JSON creation showing error on array

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;
    
}

Upvotes: 0

Views: 35

Answers (1)

Suspicio
Suspicio

Reputation: 341

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]

Upvotes: 2

Related Questions