- Home /
Question by
AlreedyTaken · Apr 19, 2017 at 01:14 PM ·
arraynullreferenceexceptioneditfixed
[Fixed] Editing an array from another class (nullReferenceError)
Hey there
I'm trying to edit an array from another class but I'm having problems instantiating it, I think. I tried it with a normal float and it works just fine.
The class with the array is in the same script as te class trying to change it. Here's the code:
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/playerInfo.dat", FileMode.Open);
PlayerData pd = new PlayerData();
pd.playerPos[0] = new PlayerData().playerPos[0]; //NullReferenceException: Object reference not set to an instance of an object
pd.playerPosX = player.transform.position.x; //works
pd.playerPos[0] = player.transform.position.x; //if i dont have the above instantiation try i get the error here
bf.Serialize(file, pd);
file.Close();
}
}
[Serializable]
public class PlayerData
{
public float playerPosX;
public float[] playerPos;
}
Please let me know if you need more information.
Thanks in advance
Edit01: Fix pd.playerPos[0] = new PlayerData().playerPos[0];
had to be changed to pd.playerPos = new float[10];
while 10 is the arraylength.
In short I'm stupid and tried to instantiate the array at index 0, but it's true that you have to instantiate the array and not the float.
Comment