Changing several variables in methods in C# for Main() to recognize - c#

I declared two variables in Main and changed both of them in a non static Method which receives a few variables(including the two I changed) and returns another, but Main doesn't recognize the change to the other variables after I use return();, and the values keep resetting. How can I make it recognize the changes?
string Attack(int Mhp, int Chp, int Cdmg, int Mdmg, string charname)
{
string res;
Mhp -= Cdmg;
Chp -= Mdmg;
Console.WriteLine();
res=charname + "'s Health has been reduced to " + Chp +", and Monster's Health reduced to " + Mhp;
return(res);
}
Mhp and Chp remain the same as I declared them in Main();, making my code pointless if the characters' health keeps resetting.
Thanks in advance!

Use
string Attack(ref int Mhp, ref int Chp, int Cdmg, int Mdmg, string charname)
When you want to do change in value type inside a procedure, it has to be passed by reference. This is C# trivia - read something on it :)

Integer is a value type, which passed to method by copy, not by reference. You are changing copy and original value stays same. Either pass value types by reference, or create reference type Character which will hold integer values, and pass character to this method.
public class Character
{
private int health;
public event Action<Character> HealthChanged;
public Character(string name, int hp, int cdmg)
{
Name = name;
health = hp;
Damage = cdmg;
}
public string Name { get; private set; }
public int Damage { get; private set; }
public bool IsAlive { get { return Health > 0; } }
public int Health
{
get { return health; }
private set
{
if (!IsAlive)
return;
health = value;
if (HealthChanged != null)
HealthChanged(this);
}
}
public void Attack(Character target)
{
if (IsAlive)
target.Health -= Damage;
}
}
This class has event to notify game core about character health changed (consider to notify about healing also). In Main create both characters and subscribe to health changing event. Then start fight:
var character = new Character("Bob", 100, 70);
character.HealthChanged += CharacterHealthChanged;
var monster = new Character("Monster", 200, 10);
monster.HealthChanged += CharacterHealthChanged;
while (character.IsAlive && monster.IsAlive)
{
character.Attack(monster);
monster.Attack(character);
}
Event handler:
static void CharacterHealthChanged(Character characer)
{
if (!characer.IsAlive)
Console.WriteLine("{0} was killed", characer.Name);
else
Console.WriteLine("{0}'s health reduced to {1}",
characer.Name, characer.Health);
}
Output
Monster's health reduced to 130
Bob's health reduced to 90
Monster's health reduced to 60
Bob's health reduced to 80
Monster is dead

primitives are handed over to a function by value, not by reference ... so you are changing a copy of your variable ... the original never sees that change ...

You have to explicitly reference them:
int something = 5;
CallMethod(ref something);
private void CallMethod(ref int x) {
x += 10;
}
Console.WriteLine(something); // Output: 15
The way you are doing it now will only change the values inside your method but will not reflect these changes to the variable outside of it. Integers are value types which means they will be sent by value. You have to explicitly define them to be sent as a reference.

In my opinion it would be better to declare Mhp and Chp (or the structure/class containing them) globally in the class.
If you really want to have them declared in your main, use the ref keyword so that the program will pass to the attack function a reference to your main's var, and not a shallow copy containing the values taken from them at the time the call to attack is being issued
string Attack(ref int Mhp, ref int Chp, int Cdmg, int Mdmg, string charname)
Note that the first approach I suggested is a lot easier (declaring class-level vars) because that way they will be accessible directly (and not by reference) by any member method of your class.
Cheers

Related

How to store a variable's value in a list and not have it changed when that variable is altered?

I'm trying to have a list that stores the current position of a character inside it, as well as previous positions. Before this code begins, the characters moves one column/row and has it's current_position is updated in another method. If the list of positions becomes bigger than (move_counter+1), the first item is removed.
However, when I run this part of the code, the current_position which was previously stored in the list is also changed.
So let's say we begin with a list: {[6,7],[7,7]} and current position [7,7]. (these are the default initial values I feed into it, [6,7] being a random starting position and [7,7] the initial current_position)
After one move to position [8,7], the list immediately changes to {[6,7],[8,7]}. Then when running the code, it becomes {[8,7],[8,7]}, when it should've been {[7,7],[8,7]}, storing the last known current_position and the current current_position.
list_size= known_cells.Count;
known_cells.Add(current_position);
if (list_size > (move_counter + 1))
{
dataGridView1.Rows[known_cells[0][0]].Cells[known_cells[0][1]].Style.BackColor = Color.LightGray;
known_cells.RemoveAt(0);
}
Hope this wasn't too chaotic an explanation. Thanks in advance for the help.
I suspect your current_position is some reference type. When you then do known_cells.Add(current_position), you are not adding the current value, but a reference to that value.
When you later change the properties, those changes are also seen though that reference in the list.
Solution: change to an "immutable" class. So instead of
class ThePosition
{
public int Coord1 {get; set;}
public int Coord2 {get; set;}
public ThePosition() {}
// default constructor that will also be added by the compiler
}
make sure that the properties cannot be changed:
class ThePosition
{
public int Coord1 {get; private set;}
public int Coord2 {get; private set;}
public ThePosition(int c1, int c2)
{
Coord1 = c1; Coord2 = c2;
}
// no default constructor!
}
So you will need to create a new instance to store a different position: current_position = new ThePosition(7,8);.
The list is {[8,7],[8,7]} because you have updated the current position to [8,7] before this piece of code.
To break it down,
The list becomes {[6,7],[8,7]}.
Then, known_cells.Add(current_position); will add the current position [8,7]. So the list becomes {[6,7],[8,7],[8,7]}.
Now the 'if' condition will remove the first element [6,7].
Hence you are left with the list {[8,7],[8,7]}
I suggest you add [8,7] rather than replacing [7,7] with [8,7] and then remove the first element.
Hope this wasn't too chaotic an explanation :)
class Coord()
{
int x = 0;
int y = 0;
public Coord(int x,int y)
{
x=x;
y=y;
}
}
class Game()
{
List<Coord> coords = new List<Coord>();
public void AddCoord(Coord c)
{
coords.Add(c);
if(coords.Count>maxAmount)
{
coords.RemoveAt(0);
}
}
}

How get set property works in C#?

I am new to C# and am exploring the very basic of C# get and set properties. What I have found is, The get set accessor or modifier mostly used for storing and retrieving value from the private field.
In this case, What is the problem with using public fields?
Another thing, I have written some conditions inside get and set. The code is
public int Number
{
get
{
if(Number>10)return 10;
else
{
return Number;
}
}
set
{
if (value > 10)
{
Number = 10;
}
else
{
Number = value;
}
}
}
Whats the problem here?
And another interesting thing is, in VS, the recursive sign appears where I check the conditions.Can someone explain it, please?
I am new to C# and wants to learn from the basic.
Thanks in advance.
Initial Problem - StackOverflow
The problem is that you are inadvertently using recursion, which is going to lead to a stack overflow, because your getters and setters for the Number property are getting and setting the Number property, rather than a backing field.
It should at the very least be changed to this:
private int number;
public int Number
{
get
{
if(this.number>10)return 10;
else
{
return this.number;
}
}
set
{
if (value > 10)
{
this.number = 10;
}
else
{
this.number = value;
}
}
}
You are missing a private backing field. Your property is self-referencing (hence the recursion symbol).
Try this instead:
private int _number;
public int Number
{
get
{
if(_number > 10)
{
return 10;
}
else
{
return _number;
}
}
set
{
if (value > 10)
{
_number = 10;
}
else
{
_number = value;
}
}
}
As far as I can tell you are calling the Number several times inside your code.
And the recursive loop will run forever until it runs into a StackOverflow :)
I ran your code with :
this.Number = 100;
int num = this.Number;
Basically this should trigger the setter and the getter. When the if clause is setting the number to 10, the first recursion is entered since you are setting the number again. It will try to set the number to 10 recursively by Number=10
Add a backing field above number, like this:
private int number; // Backing field
public int Number
{
get { return number; } // Getter
set { number = value; } // Setter
}
The main idea of a property with public read/write access is to simply be a mutator and accessor for the internal state of their containing object.
When you have conditional logic inside these get/set methods their "contract" with consumers of the class is being broken....when I call the accessor/getter
var number = anInstance.Number;
...I expect to receive the current state of the anInstance object's number, not some logic-driven derivative of it. Similarly for the Mutator/setter
anInstance.Number = 123;
...I expect that to automatically set the internal state of the anInstance object's number.
If i set the Number in one statement...
anInstance.Number = 123; // I expect anInstance to have an internal state of 123 for it's Number
var x = anInstance.Number; // I expect 123 back, not 10
...if I then retrieve that value on the next line, I expect the same value back, but with your current implementation (if it wasn't also recursive - see below), when I set Number to 123, this is being ignored and the value of 10 is saved as the new internal state and when I then retrieve Number I would get back a value of 10.
It is not the concern of the Number property to be changing what the caller has requested be set as it's value. An invoker of the Number property rightly expects it's instructions to be followed and the invoker shouldn't have to know about weird internal getter-setter logic in order to function.
If you really need to get/set things in a conditional way, the place for the conditional logic is outside the class containing the Number property, i.e. replace the Number property with a simple auto-implement getter-setter and use in the following way.
int x = anInstance.Number > 10 ? 10 : anInstance.Number; // replaced getter logic outside the class containing the `Number` property
anInstance.Number = x > 10 ? 10 : x; // replaced setter logic
As for the reason why you are seeing the recursion symbol, that is because your code is recursively calling itself. The Number property is calling itself, instead of some backing field. Change the property to be like...
private int number;
public int Number
{
get
{
return number; // note the lower-case 'n' refers to the private field instead of the property
}
set
{
number = value;
}
}
Note, though, that there is no need to have a private backing field when you use your property in this simple way. If the intent is to have full read-write access, you could simply use a public field.
public int Number;
However, a property allows you to control access to fields, e.g.
public int Number { get; private set; }
which a simple public property does not allow, although you can use the readonly modifier to give this behaviour.
public readonly int Number;
However, another advantage of using a property over using a field is that it can offer greater control over how internal state is used/stored, e.g.this example is taken from MSDN
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
In this example, the caller of this class' Hours property is getting and setting a value of hours but under the hood the internal state of the class is storing/retrieving using seconds. This would not be possible with a public field.

Method within a class won't take away value from integer argument

I've currently only been learning C# for a week so apologies for any stupid errors but I'm trying to call a method within a switch statement to take away an integer value that is declared within a list from the argument given to the method, the argument in this case is the health of the currEnemy object, but when the currEnemy.health value is printed out to the console it's value is unchanged and I can't figure out why.
The list that stores the integer value that the currEnemy.health is taken away by a long with the health variable which is set to an integer value in the Enemy class:
public List<Weapon> myWepList = new List<Weapon>(){
new Weapon {name = "Dagger", dmg = 10, stamDrain = 5},
new Weapon {name = "Sword", dmg = 20, stamDrain = 20},
new Weapon {name = "Halberd", dmg = 40, stamDrain = 20}
};
public int health{ get; set; }
The method within the player class that should take away the 'dmg' value from the enemy.health value and set enemy.health to a new value:
public void charAttack(int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
Then the code that calls the above method to display the currEnemy.health's new value:
enum PlayerInput
{
Attack,
Block,
}
while (gameStart == true) //this part onwards is stored in the main method
{
string playerInput = Console.ReadLine().ToUpper();
PlayerInput inputChoice;
Console.WriteLine("Type 'attack' to attack the enemy");
if (Enum.TryParse<PlayerInput>(playerInput, true, out inputChoice))
{
switch (inputChoice)
{
case PlayerInput.Attack:
currPlayer.charAttack(currEnemy.health);
Console.WriteLine("Enemy Health is {0}", currEnemy.health);
break;
default:
break;
}
}
}
I'd also appreciate if any general advice is just given to me about my code considering I'm completely new to C# so any constructive advice would be great, thank you.
This method:
public void charAttack(int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
... is basically pointless. The statement enemyHealth -= ... only affects the parameter called enemyHealth. It won't change currEnemy.Health at all - because the method argument is passed by value. In other words, the process is:
currEnemy.health is evaluated
The value is used as the initial value for enemyHealth
The method executes
The final value of enemyHealth isn't used at all
See my article on parameter passing for more details.
There are various ways you could tackle this - for example, you might want:
currPlayer.Attack(currEnemy);
where the Attack method would look something like:
public void Attack(Enemy enemy)
{
Weapon weapon = equippedWep[0];
enemy.Health -= weapon.Damage;
}
Note that the last line is very different to your previous code, because it would set the value of enemy.Health afterwards... you wouldn't just be changing a parameter, but the state of an object.
You can't change a value that is passing to a function. It is the same in all langages, not only C#.
int a = 0;
function changeA(int a)
{
a = 1;
}
print a; // show 0, not 1
You can change a value that is contained into an object:
public class Obj
{
public int health{ get; set; }
}
var o = new Obj();
function changeHealth(Obj o)
{
o.health = 1;
}
print o.health; // show 1
C# or whatever, that is the first thing you need to understand.
For your actual problem, here is a proposal: pass the actual object representing the enemy, not just his health. Then deduce the health of the enemy object.
public void charAttack(Player enemy)
{
enemy.health -= equippedWep[0].dmg;
}
while (gameStart == true) //this part onwards is stored in the main method
{
string playerInput = Console.ReadLine().ToUpper();
PlayerInput inputChoice;
Console.WriteLine("Type 'attack' to attack the enemy");
if (Enum.TryParse<PlayerInput>(playerInput, true, out inputChoice))
{
switch (inputChoice)
{
case PlayerInput.Attack:
currPlayer.charAttack(currEnemy);
Console.WriteLine("Enemy Health is {0}", currEnemy.health);
break;
default: break;
}
}
}
C# passes ints by value which means that you only get a copy of the value in the method. To solve it you can parse the enemy object instead like this:
public void charAttack(Enemy enemy)
{
enemy.health -= equippedWep[0].dmg;
}
This would affect the health on the enemy object.
The problem lies in your charAttack method declaration. The enemyHealth parameter is not being passed by reference, so you are actually modifying a copy of the variable not the original (this is call passing by value).
You can either pass the parameter by reference, which will mean that you modify the original:
public void charAttack(ref int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
Or you could return the modified result and set your original value to it:
public int charAttack()
{
return equippedWep[0].dmg;
}
i = charAttack();
You need to pass your enemyHealth value by reference. C# defaults to passing by value which means the method gets it own copy of the value. To pass the actual int object pass by reference.
public void charAttack(int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
Based on the above method, the behavior you're experiencing is expected. You are not actually stating "change the calling currEnemy.health" when calling this method, but change enemyHealth. The problem is currEnemy.health is being passed by value (as in the literal value is passed, not the "object" that represents that value) not by reference.
There are two (or more) ways to fix this:
one would be use a ref to the enemy health:
public void charAttack(ref int enemyHealth)
{
enemyHealth -= equippedWep[0].dmg;
}
and call your method like:
currPlayer.charAttack(ref currEnemy.health);
or return a new enemy health from your method:
public int charAttack(int enemyHealth)
{
return enemyHealth - equippedWep[0].dmg;
}
and call like:
currEnemy.heatlh = currPlayer.charAttack(currEnemy.health);

How can I access a member from another class with a Timer?

I'm currently writing a class to calculate the average download speed over a defined period of time, taking a defined number of samples. The way I thought this would work is that this class runs a Timer object, which calls a method inside said class that will look at the bytes downloaded (maintained in a parent class, the FTPDownloadFile), and then store that sample in a Queue. My issue is accessing the number of bytes downloaded, however.
My method of accessing that information was through a reference that was passed in when the download calculating class was constructed, however, it seems like I'm not understanding/using references correctly. The variable that is passed in always appears to be 0, even though I can see the original variable changing.
Can anyone tell me what I'm doing wrong / suggest a better way for me to accomplish what I want to do?
First, here is the class that is handling the calculation of the download speed:
public class SpeedCalculator
{
private const int samples = 5;
private const int sampleRate = 1000; //In milliseconds
private int bytesDownloadedSinceLastQuery;
private System.Threading.Timer queryTimer;
private Queue<int> byteDeltas = new Queue<int>(samples);
private int _bytesDownloaded;
public SpeedCalculator(ref int bytesDownloaded)
{
_bytesDownloaded = bytesDownloaded;
}
public void StartPolling()
{
queryTimer = new System.Threading.Timer(this.QueryByteDelta, null, 0, sampleRate);
}
private void QueryByteDelta(object data)
{
if (byteDeltas.Count == samples)
{
byteDeltas.Dequeue();
}
byteDeltas.Enqueue(_bytesDownloaded - bytesDownloadedSinceLastQuery);
bytesDownloadedSinceLastQuery = _bytesDownloaded;
}
/// <summary>
/// Calculates the average download speed over a predefined sample size.
/// </summary>
/// <returns>The average speed in bytes per second.</returns>
public float GetDownloadSpeed()
{
float speed;
try
{
speed = (float)byteDeltas.Average() / ((float)sampleRate / 1000f);
}
catch {speed = 0f;}
return speed;
}
That class is contained inside of my FTPDownloadFile class:
class FTPDownloadFile : IDisposable
{
private const int recvBufferSize = 2048;
public int bytesDownloaded;
public SpeedCalculator Speed;
private FileStream localFileStream;
FtpWebResponse ftpResponse;
Stream ftpStream;
FtpWebRequest ftpRequest;
public List<string> log = new List<string>();
private FileInfo destFile;
public event EventHandler ConnectionEstablished;
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator(ref bytesDownloaded);
}
public void GetFile(string host, string remoteFile, string user, string pass, string localFile)
{
//Some code to start the download...
Speed.StartPolling();
}
public class SpeedCalculator {...}
}
This is a common 'issue' with understanding 'ref' parameters in C#. You see, unlike C+, there are no real value references in C#.
In C++, when you pass-by-reference, you actually internally pass pointer to the variable. Therefore, you can have a class member variable of type "int&" that is actual reference to an integer stored elsewhere.
In C#, 'ref' or 'out' parameter works in a similar way, but noone talks about pointers. You cannot store the reference. You cannot have a 'ref' class member. Look at your class: the sotrage variable is of type 'int', plain 'int', not a reference.
You actually are passing that value by-ref, but then you copy it to the member variable. The 'reference' is gone at the point where your constructor ends.
To walk it around, you have to keep the actual source object, and either introduce a strong dependency, or a weak one by an interface, or do it lazy/functional way - by a delegate
Ex#1: strong reference
public class SpeedCalculator
{
private const int samples = 5;
private const int sampleRate = 1000; //In milliseconds
private int bytesDownloadedSinceLastQuery;
private System.Threading.Timer queryTimer;
private Queue<int> byteDeltas = new Queue<int>(samples);
private FTPDownloadFile downloader; // CHANGE
public SpeedCalculator(FTPDownloadFile fileDownloader) // CHANGE
{
downloader = fileDownloader;
}
public void StartPolling()
{
queryTimer = new System.Threading.Timer(this.QueryByteDelta, null, 0, sampleRate);
}
private void QueryByteDelta(object data)
{
if (byteDeltas.Count == samples)
{
byteDeltas.Dequeue();
}
byteDeltas.Enqueue(_bytesDownloaded - bytesDownloadedSinceLastQuery);
bytesDownloadedSinceLastQuery = downloader.bytesDownloaded; // CHANGE
}
//and in the other file
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator( this ); // CHANGE
}
In C#, every object (class MyObject) is passed by reference, or implicit pointer, therefore taking FTPDownloadFile by parameter and assigning it to a member variable does not copy it, it is truly passed by ref (on the other hand, values (int, decimal, ..) and structs (struct MyThing) are always passed by value, so your original _bytes = bytes made a copy of int). Hence, later, I can just query the
Ex#2: "weak" reference
public interface IByteCountSource
{
int BytesDownloaded {get;}
}
public class FTPDownloadFile : IDisposable, IByteCountSource
{
.....
public int BytesDownloaded { get { return bytesDownloaded; } }
.....
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator( this ); // note no change versus Ex#1 !
}
}
public class SpeedCalculator
{
....
private IByteCountSource bts;
public SpeedCalculator(IByteCountSource countSource) // no "FTP" information!
{
this.bts = countSource;
}
...
private void QueryByteDelta(object data)
{
....
bytesDownloadedSinceLastQuery = bts.BytesDownloaded;
}
The first example was quick and dirty. In general, we usually want the classes to know as least as possible about all other. So why should the SpeedCalculator know about the FTPDownloadFile? All it needs to know is the current byte-count. So I introduced an interface to 'hide' the actual source behind. Now the SpeedCalculator can take the value from any object that implements the interface - be it FTPDownloadFile, HTTPDownloadFile or some DummyTestDownloader
Ex#3: delegates, anonymous functions, etc
public class SpeedCalculator
{
....
private Func<int> bts;
public SpeedCalculator(Func<int> countSource)
{
this.bts = countSource;
}
...
private void QueryByteDelta(object data)
{
....
bytesDownloadedSinceLastQuery = bts();
}
// and in the other file
private int getbytes() { return bytesDownloaded; }
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator( this.getbytes ); // note it is NOT a getbytes() !
}
// or even
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator( () => this.bytesDownloaded ); // CHANGE
}
The example with an interface is pretty, but the interface was 'small'. One is ok, but sometimes you'd need to introduce dozens of such one-property or one-method interfaces, it gets somewhat boring and cluttering. Especially if all of that is 'internal implementation' that anyways isn't published for any other people to use. You can very easily drop such small interface with a short lambda, as in the third example. Instead of receiving and storing a object-that-implememts-an-interface, I changed the parameter to Func. This way I require to get "a method that returns an INT". Them, I pass the some method. Note that during new SpeedCalculator, I do not call the this.getbytes(), I pass the method without parenthesis - this causes the method to be wrapped into Func delegate, that will be later invoked as bts(), and will return current counter. This getbytes is rarely used, only in this one place - so I can even drop it completely and write anonymous function right at the point of constructor call, as you can see in the "or even" part.
However, I'd suggest you to stick with interfaces for now, they are much clearer to read and understand.

C# creating a Class, having objects as member variables? I think the objects are garbage collected?

So I have a class that has the following member variables. I have get and set functions for every piece of data in this class.
public class NavigationMesh
{
public Vector3 node;
int weight;
bool isWall;
bool hasTreasure;
public NavigationMesh(int x, int y, int z, bool setWall, bool setTreasure)
{
//default constructor
//Console.WriteLine(x + " " + y + " " + z);
node = new Vector3(x, y, z);
//Console.WriteLine(node.X + " " + node.Y + " " + node.Z);
isWall = setWall;
hasTreasure = setTreasure;
weight = 1;
}// end constructor
public float getX()
{
Console.WriteLine(node.X);
return node.X;
}
public float getY()
{
Console.WriteLine(node.Y);
return node.Y;
}
public float getZ()
{
Console.WriteLine(node.Z);
return node.Z;
}
public bool getWall()
{
return isWall;
}
public void setWall(bool item)
{
isWall = item;
}
public bool getTreasure()
{
return hasTreasure;
}
public void setTreasure(bool item)
{
hasTreasure = item;
}
public int getWeight()
{
return weight;
}
}// end class
In another class, I have a 2-Dim array that looks like this
NavigationMesh[,] mesh;
mesh = new NavigationMesh[502,502];
I use a double for loop to assign this, my problem is I cannot get the data I need out of the Vector3 node object after I create this object in my array with my "getters".
I've tried making the Vector3 a static variable, however I think it refers to the last instance of the object. How do I keep all of these object in memory? I think there being garbage collected. Any thoughts?
In C#, don't build get and set functions like that. Use a property:
public float X
{
get {Console.WriteLine(node.X); return X;}
}
public bool IsWall {get;set;}
If you have a reference to these items, they are not garbage collected.
If you are maintaining a reference to them, they are guaranteed to NOT get garbage collected.
I don't see where you are defining node. Is it possible that another piece of code is interfering with it? Is it declared static? If it is declared static, there is only one instance of it (instead of one per class), and this could be the source of some confusion.
Why is your node field declared public?
I would put that in a property, and set a breakpoint on the set accessor, so that you can see where it is getting modified.
Vector3 is a struct, so it is not an object. It is a value. This means that it is definitely not being garbage collected.
It is a value type, so every time you pass it along a copy is made. Could it be that you get a copy and modify that? It is not clear to me what you mean, when you say you can't get data out of node.
In the class definition everything seems kosher to me except the fact the the node field is declared public - you should avoid this, but I hope you do not assign null to it.
If you do not your Vector object will not be garbage collected.
So what exactly is happening when you try to access the getters? Does GetX throw a null pointer exception?
We cannot see what code you are using to instantiate the 502 by 502 array: Are you sure you are instantiating a new node for every one? If yes, than you should easily be able to retrieve the properties. mesh[x,y].getWall() would give you the correct value for given x's and y's.

Categories