Here is the function GetValidActionGridPositionList inside the ShootAction class.
public List<GridPosition> GetValidActionGridPositionList(GridPosition unitGridPosition)
{
List<GridPosition> validActionGridPositionList = new();
for (int x = -maxShootDistance; x <= maxShootDistance; x++)
for (int z = -maxShootDistance; z <= maxShootDistance; z++)
{
GridPosition possibleGridPosition = unitGridPosition + new GridPosition(x, z);
// Grid pos is invalid, or doesn't have any unit
if (!LevelGrid.Instance.GridPosIsValid(possibleGridPosition) ||
!LevelGrid.Instance.GridPosHasAnyUnit(possibleGridPosition))
continue;
int distance = unitGridPosition.Distance(possibleGridPosition);
// Grid pos is too far away
if (distance > maxShootDistance)
continue;
Unit theTargetUnit = LevelGrid.Instance.GetUnitAtGridPos(possibleGridPosition);
// Both units are on the same 'team'
if (theTargetUnit.IsEnemy() == unit.IsEnemy())
continue;
Vector3 unitWorldPosition = LevelGrid.Instance.GetWorldPos(unitGridPosition);
Vector3 shootDir = theTargetUnit.GetWorldPosition() - unitWorldPosition.normalized;
const float unitShoulderHeight = 1.7f;
bool obstacleHit = Physics.Raycast(unitWorldPosition + Vector3.up * unitShoulderHeight,
shootDir,
Vector3.Distance(unitWorldPosition, theTargetUnit.GetWorldPosition()),
obstaclesLayerMask);
if (obstacleHit)
continue;
validActionGridPositionList.Add(possibleGridPosition);
}
return validActionGridPositionList;
}
I have it almost identical as Hugo´s except for one modification I made on purpose. I changed this variable name Unit theTargetUnit = LevelGrid.Instance.GetUnitAtGridPos(possibleGridPosition);
from targetUnit to theTargetUnit (couldnt come up with a better name).
The reason I did this is related to my question. Before renaming, my IDE warned me that the name targetUnit was hiding a field with the same name in the class. That is indeed the case.
So my question is, why did we declare a variable in the scope of only this method with the same name? I see two options:
- This variable is not related to the field of the class, in that case I would prefer for it to have a different name, to avoid this confusion
- This variable is exactly the same as the field in the class, in that case I would not make it a new variable in this scope, and just assign the field of the class.
Thats basically my question, is the case one of the above, or other that I couldnt think of.
Thanks!