[SOLVED] Constructors with unexpected default values
Hi all. I am relatively new to coding and game development, and i'm working on a little project that i'm letting grow small step by small step. It is a Tile-TurnBased chesslike game.
I am having some sort of "silly" problem with constructors and I really can't get to decipher C# MSDN guides.
In particular i have two problems: 1. i have my Tile class which is:
public class Tile
{
public int dimensioneTile;
public int xRel;
public int yRel;
public bool tileOccupata;
public Tile(int _xRel, int _yRel, bool _occupata)
{
xRel = _xRel;
yRel = _yRel;
tileOccupata = _occupata;
}
(tileOccupata is a "isOccupied" sort of bool) it works actually, but since all of my tiles "are born" empty I would like to have somthing like:
public class Tile
{
public int dimensioneTile;
public int xRel;
public int yRel;
public bool tileOccupata;
public Tile(int _xRel, int _yRel)
{
xRel = _xRel;
yRel = _yRel;
tileOccupata = false;
}
}
Where the variable already stores the information of being "empty", but if i code it like so it stores it as true, ignoring my line of code saying "tileOccupata = false"... this is not the behavior i was expecting.
My second problem is similar but slightly different
public class Eroe
{
public string nome;
public int Strength;
//i want health to be Strength * 2
public int Health;
//constructor
public Eroe(string _nome, int STR)
{
nome = _nome;
Strength = STR;
Health = Strength * 2;
//i also tried Health = STR * 2
}
}
in both cases Health turns out to be 0
So my actual question is: do i need to have a parameter for each variable i have in my class for it to be actually initialized at a different value than 0 || true? How can I do it?
Thank you for your help
How are you calling these? In the first case tileOccupata should definitely be false. It should be false even if you don't set it since that is the default value. I would guess you're setting it elsewhere.
The second case is similar - if you're passing in a non-zero value for STR then Health should be set to double that. It's also public so could be set elsewhere.
I am pretty sure that i don't set them elsewhere. I actually never call it except in "Debug.Log" when i call the constructor like Eroe pawn = new Eroe(pawn, 5); Debug.Log(pawn.Health); it prints 0.
same with Tile.tileOccupata; it prints true. No idea why
btw i will duoblecheck
Answer by BeardyRamen · Dec 10, 2015 at 08:05 PM
I found the error. As I thought it was a noob one. I had stored some "Eroe" before i added the variable "Health". I was running the game using the old instances that didn't have Health set