I have 2d array storing gameObjects and a method for updating logic. Here is the 1st code:
public void UpdatePlayerPosition(Vector3 posStart, Vector3 posEnd)
{
_levelItems[(int)posEnd.x, (int)posEnd.z] = _levelItems[(int)posStart.x, (int)posStart.z];
_levelItems[(int)posStart.x, (int)posStart.z] = null;
}
Here is the 2nd code
public void UpdatePlayerPosition(Vector3 posStart, Vector3 posEnd)
{
var placeStart = _levelItems[(int)posStart.x, (int)posStart.z];
var placeEnd = _levelItems[(int)posEnd.x, (int)posEnd.z];
placeEnd = placeStart;
placeStart = null;
}
The 1st code is working fine however I would like it to be more readable like the 2nd that is not working. I know about the vars refs and value stuff so I know why it is not working properly. Is there any way to make it work properly and look good ? The best I can do is
public void UpdatePlayerPosition(Vector3 posStart, Vector3 posEnd)
{
var placeStart = _levelItems[(int)posStart.x, (int)posStart.z];
var placeEnd = _levelItems[(int)posEnd.x, (int)posEnd.z];
_levelItems[(int)posEnd.x, (int)posEnd.z] = placeStart;
_levelItems[(int)posStart.x, (int)posStart.z] = null;
}
CodePudding user response:
The 2nd code will not work because you are just assigning the value of _levelItems[(int)posStart.x, (int)posStart.z]
and _levelItems[(int)posEnd.x, (int)posEnd.z]
to placeStart
and placeEnd
respectively. Then you just change the value of the later 2 variables and not the array. You must change the value to the array variables directly to change them.
In my opinion, a more clean code will be like this:
public void UpdatePlayerPosition(Vector3 posStart, Vector3 posEnd)
{
int xStart = (int)posStart.x;
int zStart = (int)posStart.z;
int xEnd = (int)posEnd.x;
int zEnd = (int)posEnd.z;
_levelItems[xStart, zStart] = null;
_levelItems[xEnd, zEnd] = placeStart;
}