c# - When i edit one instance's variable values the others another instance's change too -
i have 2 classes, 'unit' , 'tile'. both of these have 'location' class in them so...
class unit { // add stats name , health, speed , strength. public stats stats = new stats(); // add location coordinates public location location = new location(); } public class tile { // add stats name , health, speed , strength. public stats stats = new stats(); // represents ability move out of tile via either {north,east,south,west}; public list<bool> movementdirections = new list<bool>() { true, true, true, true }; // represents coorinates access tile. public location location = new location(); } ok so... you'll notice have 'stats' class on both. both 'unit' , 'tile' new instances , both have new instances of 'stats' , 'location' on them.
my issue have got small piece of code changes location of unit , it's acting strangely.
static void move(tile tile,int[] coordschange,unit unit) { // unit player defined earlier in script new unit(). player.stats.name = "hendry";// check. doesn't change tile name player.location.x = player.location.x + coordschange[0]; // these both change tile location also. player.location.y = player.location.y + coordschange[1]; } since new instance , changing of player stats isn't changing tile stats have no idea why location change player. have tested visa versa , same happens ... it's though location classes linked stats classes not despite no difference in them.
here classes btw.
public class location { private int _x = 0; private int _y = 0; public int x { { return _x; } set { _x = value;} } public int y { { return _y;} set { _y = value; } } } public class stats { public string name = "default"; public string classname = "default"; public int health = 10; public int strength = 5; public int defence = 5; public int speed = 5; public int intelligence = 5; } any ideas appreciated.
thanks zorilya
the importance of encapsulation:
class unit { // add stats name , health, speed , strength. public stats stats { get; private set; } // add location coordinates public location location { get; private set; } public unit() { location = new location(); stats = new stats(); } } same tile.
update
my theory before call of move have code assigning:
player.location = tile.location; or
tile.location = player.location; making location property private setter, cause compiler error such code.
update
public class location { ... code ... public void assign(location asource) { x = asource.x; y = asource.y; } } tile.location.assign(player.location);
Comments
Post a Comment