Why does this give null exception?

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

public class Saving : MonoBehaviour {

    public Save myData;

    void Update(){

        if (Input.GetKeyDown ("s")){

            myData = new Save(); // Clears old data

            int partCount = Ref.currentlyInControl.connectedParts.Length;

            myData.partsSave = new PartSave[partCount];

            for (int i = 0; i < partCount; i++){ // Loops once for each part

                myData.partsSave [i].partId = 0; // This line is giving me ther error, why?
            }
        }
    }
}

[System.Serializable]
public class Save {

    public PartSave[] partsSave;
}

[System.Serializable]
public class PartSave {
    [Header("Part")]
    public int partId;

    public Vector2 pos;
}

The error always shows up when I try access “partsSave” what is the problem?

Well, you ony created an array, but the array is still empty. You’ll need to create an instance of PartSave for each index of the array to be able to set an id:

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

public class Saving : MonoBehaviour 
{

    public Save myData;

    void Update()
    {

        if (Input.GetKeyDown ("s"))
        {

            myData = new Save(); // Clears old data

            int partCount = Ref.currentlyInControl.connectedParts.Length;

            myData.partsSave = new PartSave[partCount];

            for (int i = 0; i < partCount; i++)
            { // Loops once for each part

                myData.partsSave [i] = new PartSave
                {
                    PartId = 0
                };
            }
        }
    }
}

[System.Serializable]
public class Save 
{
    public PartSave[] partsSave;
}

[System.Serializable]
public class PartSave 
{
    [Header("Part")]
    [SerializeField]
    private int partId;

    [SerializeField]
    private Vector2 pos;
   
    public int PartId 
    { 
        get { return partId; }
        set { partId = value; } 
    }
   
    public Vector2 Pos
    { 
        get { return pos; }
        set { pos = value; } 
    }
}
if (Input.GetKeyDown ("s")

Instead of

if (Input.GetKeyDown (KeyCode.S))

?

GetKeyDown also has a version with string parameter :wink: Though the KeyCode variant is obviously less error prone and should be used whenever possible.

[System.Serializable]
public class Save {
    public PartSave[] partsSave;
}

[Pedantic mode triggered]

Nope, the array is not created so it can’t be empty. The array is just declared in the Save class, and not assigned. Therefore it’s null.
Note that you can create a proper empty array:

int[] someArray = new int[0].

He did create it with the following:

myData.partsSave = new PartSave[partCount];

@Timelog
Sorry. I somehow thought that’s the part you’ve fixed. So, it was the elements of the array that was not created.