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