简体   繁体   中英

Object reference not set to an instance of an object error?

and in my c# program, what i am trying to do is whenever in a game you say !mypickaxe, it tells you what pickaxe you have. Recently I figured out a way to save it to a .txt file so the data could be used more than one time, but of course im getting "object reference not set to an instance of an object". Here is the part that has the error:

StreamReader streemy = new StreamReader("pickaxes.txt");
string line = streemy.ReadLine();
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);

In the .txt file, it saves like this: username=pickaxe And so it's supposed to get the number, but i get that error on this line:

string[] thing = line.Split('=');

Does anybody know how to fix this and/or why this happens? Thanks in advance!

try and check if streemy.ReadLine returns null:

string line = streemy.ReadLine();

if(!string.IsNullOrEmpty(line))
{
  string[] thing = line.Split('=');
  player[userID].pickaxe = Convert.ToInt32(thing[1]);
}

you could even go futher and check thing and player[userID]

if(!string.IsNullOrEmpty(line))
{
  string[] thing = line.Split('=');
  if(thing.Count() > 1 && player[userID] != null)
    player[userID].pickaxe = Convert.ToInt32(thing[1]);
}

also I would wrap the stream in a using block:

using(StreamReader streemy = new StreamReader("pickaxes.txt"))
{
   //code omitted
}

i would suggest to use File.ReadAllLines() to avoid all Errors.

string [] line=System.IO.File.ReadAllLines("pickaxes.txt");    
string[] thing = line[0].Split('=');//here 0 can be any required index
player[userID].pickaxe = Convert.ToInt32(thing[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM