I'm striking a roadblock in coding. I'm coding in C#, making a program with Monogame.
I have a list of units, and I'm trying to do mouse picking with them. I shoot a ray out from the mouse into the screen, and find which object is the first one it hits.
// A method to find which units are currently under the mouse.
static public void FindPickedUnits(string ID)
{
foreach (Unit unit in ListDictionary[ID])
{
// Run the code to check whether or not it is picked, and returns a float representing how close it is.
unit.IsPicked = Cursor.Pick(unit.Collisions);
// And if it is picked...
if (unit.IsPicked != null)
{
// We will clone it as the closest unit if none exist, or...
if (ClosestUnit == null)
{
ClosestUnit = unit;
}
// if one already does, overwrite it if it's even closer.
else if (unit.IsPicked < ClosestUnit.IsPicked)
{
ClosestUnit = unit;
Console.WriteLine("The new closest unit is at X" + unit.Position.X + " Y" + unit.Position.Y);
}
}
}
}
// elsewhere...
Console.WriteLine("The selected unit's color is " + ClosestUnit.Tint);
This code clones the picked unit into the ClosestUnit object, which then I can read from whenever I want, no problem.
HOWEVER
I don't want to purely read the values of the closest unit, I want to WRITE to them, and change some of them. But if I change the values of the ClosestUnit object, it doesn't reflect back to the actual unit in the list of units.
TL;DR I want to be able to single a unit out of a list of units, and then write to it elsewhere in the code. If the ClosestUnit object could function akin to a ref parameter does, directly referencing the actual unit in the list instead of being a clone, this would be easy, but I don't know how to make it do that.
What is the most efficient way to handle this problem, or avoid it?
Ironically, there was nothing wrong with my code the whole time. I didn't realize that the ClosestUnit object, by nature of being a class (a reference type), directly referenced the unit in the ListDictionary, as opposed to being a clone of it.
I could just change the values on the ClosestUnit object and it would reflect back to the original. Yay!