One Defender Per Tile Using Vector2.Distance()

I did a quick google search for checking if instances exist at a given position and came up with this solution

private void OnMouseDown()
    {
        Vector2 gridPos = GetSquareClicked();

        // if there is no defender at gridPos then attempt to place one
        if (!IsDefenderAtPoint(gridPos))
            AttemptToPlaceDefenderAt(gridPos);
    }

    private bool IsDefenderAtPoint(Vector2 gridPos)
    {
        // Find all defenders currently in play
        Defender[] defenders = FindObjectsOfType<Defender>();

        // Check each one to see if it's position is the same as the selected position 'gridPos' using Vector.Distance()
        foreach (Defender defender in defenders)
        {
            if (Mathf.Abs(Vector2.Distance(gridPos, defender.transform.position)) <= Mathf.Epsilon) // == 0 also works, Epsilon allows for small margin of error
            {
                return true;
            }
        }

        // Nothing was found, return false
        return false;
    }

Privacy & Terms