NullReferenceException: Object reference not set to an instance of an object
Hi all,
I have had a look at similar questions and none of them seem to be dealing with the same issue that I have.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class inventory : MonoBehaviour {
public string findFile()
{
string dir = System.IO.Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location);
string filePath = dir + "inventory.csv";
if (!File.Exists (filePath)) {
File.Create (filePath).Close ();
}
return filePath;
}
// Use this for initialization
public void Start ()
{
List<PlayerInventory> CharInv = new List<PlayerInventory>();
string line, fileImportPath = findFile ();
int i = 0;
using (StreamReader reader = new StreamReader (fileImportPath))
{
while ((line = reader.ReadLine ()) != null || i < 10) {
CharInv.Add(new PlayerInventory());
CharInv[i].assignItem (line);
i++;
}
reader.Close ();
}
}
}
public class PlayerInventory
{
public string Item = "";
public int numItems = 0;
public bool Use = false;
public string Description = "";
string[] part = { "", "", "", "" };
public void assignItem (string line)
{
part = line.Split (',');
Item = part [0];
numItems = int.Parse (part [1]);
Use = bool.Parse (part [2]);
Description = part [3];
}
}
Here is the error:
NullReferenceException: Object reference not set to an instance of an object
PlayerInventory.assignItem (System.String line) (at Assets/Scrips/inventory.cs:52)
inventory.Start () (at Assets/Scrips/inventory.cs:33)
I have tried to define all the variables that are used in the Class as suggested but it seems to have no effect. Can someone tell me the reason of why this is happening and how to fix it.
Thanks in advance.
EDIT:
Right I have traced the error to the data that is taken in by the class not being assigned properly.
This is the CSV file I am reading in.
Sword,1,True, A shining longsword
Medicine,3,True, To make you feel better
Gun,1,False,An old flintlock style thing
Sheild,1,True,A wooden sheild with a metal boss
From that file the previous data these are the ones that are being read in and not being read into the classes.
Yes, Yes, Yes, Yes
Yes, Yes, No, Yes
Yes, No, Yes, No
Yes, No, No, Yes
Any reason why that is?
I would put a debug into assignItem and see what comes in, end what split puts out. Since its not an ArrayOutOfBounds, part seems to be null.