I'm a c# begginer and my code generates the CS0236 error, I've created a class with a
LvlData
struct that contains a couple of variables and a readLvl
function that takes the directory of a text file and returns a LvlData
based on that.
However, when trying to use it (public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");
) it throws an A field initializer cannot reference the non-static field, method, or property 'name'. error.
Here's the LevelManager class:
class LevelManager
{
public LevelManager()
{
}
public struct LvlData
{
public LvlData(int width, int height, string tiledata,string colisiondata,string flag = "0")
{
Width = width;
Height = height;
TileData = tiledata;
CollisionData = colisiondata;
Flag = flag; //Deafult 0 Beacuse we sometimes don't have it
}
public int Width { get; }
public int Height { get; }
public string TileData { get; }
public string CollisionData { get; }
public string Flag { get; }
}
public LvlData readLvl(string dir)
{
int w, h;
string tiled, colliiond, f;
// Read the file
string[] lines = System.IO.File.ReadAllLines(dir);
w = int.Parse(lines[0]);
h = int.Parse(lines[1]);
tiled = lines[2];
colliiond = lines[3];
f = lines[4];
LvlData deta = new LvlData(w, h, tiled, colliiond, f);
return deta;
}
public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");
}
CodePudding user response:
you have to move a method call to the constructor
class LevelManager
{
public LvlData CurrentLevelData {get; set;}
public LevelManager()
{
CurrentLevelData = readLvl("../Level/Def/lvl.txt");
}
or make the method and property static, but it doesn't make much sense
public static LvlData CurrentLevelData {get; set; } = readLvl("../Level/Def/lvl.txt");
public static LvlData readLvl(string dir)
{
.....
}