Problem with Raycast2D

I’m pretty new to Unity. I’m currently working on a new project where I’m trying to use Raycast2D to hit the collider of a rectangle mark it and then move it. At the beginning the Raycast hits the Collider of the rectangle which is then also marked. However at some point only the collider of the background is being hit and the rectangle is no longer marked.

There is also a collider for the background. When I hit the background with my Raycast, the rectangle should be unmarked.

I figured out that only the collider of the background is being marked using

Debug.Log(hit.collider.gameObject.name)

Maybe someone can help me with this. Thanks a lot in advance.

Here is my code:

public RaycastHit2D hit;
public GameObject unit;
public GameObject hitmarker;
private float movementSpeed = 0.02f;
private Vector2 targetPos;

public bool isMarked = false;

private Color originalColor;
public Color marketColor = Color.yellow;

public bool isMoving;

private void Start()
{
    unit = gameObject;
    originalColor = GetComponent<SpriteRenderer>().color;
    hitmarker = GameObject.Find("Circle");
}

void Update()
{
   
    if (Input.GetMouseButtonDown(0))
    {
        SaveMouseclickPosition();
      
        if (hit.collider != null)
        {
            Debug.Log(hit.collider.gameObject.name + " Hit");
           
            if (hit.collider.gameObject == gameObject)
            {
                MarkUnit();
                targetPos = unit.transform.position;
                
            }
            if (hit.collider.gameObject != gameObject)
            { 
                UnmarkUnit();
            }
        }
    }

    if (Input.GetMouseButtonDown(1)) 
    {

        SaveMouseclickPosition();                 

        if (hit.collider != null)                                                       
        {
            Debug.Log(hit.collider.gameObject.name + " Collider Hit");

            if (hit.collider.tag == "ground")
            {
                targetPos = hit.point;
                isMoving = true;
            }
        }
    }
    Moving();
}

private void MarkUnit()
{
    GetComponent<SpriteRenderer>().color = marketColor;
    isMarked = true;
}
private void UnmarkUnit()
{
    GetComponent<SpriteRenderer>().color = originalColor;
    isMarked = false;
}

private void Moving()
{
    if (isMoving & isMarked)
    {
        unit.transform.position = Vector2.MoveTowards(unit.transform.position, targetPos, movementSpeed);

        if (unit.transform.position.x == targetPos.x && unit.transform.position.y == targetPos.y)
        {
            isMoving = false;
        }
    }
}
public void SaveMouseclickPosition()
{
    Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    hit = Physics2D.Raycast(mousePosition, Vector2.zero);
    
    hitmarker.transform.position = mousePosition;
}

Why is your raycast using zero as a direction? Use OverlapPoint if you’re not actually casting.