Raycast is not hitting collider

The following script is attached to the player of a 2D top-down game. Whenever the player clicks on the screen, the script is supposed to translate the player sprite there. That works fine, but if there is a collider in front of the player, it will try and clip into the collider. So a quick fix I thought of was just to try and detect if the player clicked on a collider, and simply ignore it.

THIS IS IMPORTANT I have heard of A(star) pathfinding and tried to implement, but me being novice and there being no tutorials for Unity 2D implementation of A(star) pathfinding on a 2D top-down game, I gave up. If you have a tutorial for this, PLEASE tell me. I would rather have pathfinding than this hack.

Now the problem seems to be that the raycast ignores ANY collider it interacts with. I do not know why this is. Every time I run the program like this, the console gives me an error saying that the “RaycastHit variable ‘hit’ is null” and cannot evaluate its layer.

Any help is extremely appreciated. Thank you!

Code:

void Update()
{    
        if (Input.GetMouseButtonDown(0))
        {    
            Vector3 dir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
            RaycastHit hit;
            Physics.Raycast(transform.position, dir, out hit);

            if (hit.collider.gameObject.layer.ToString() == "Obstacle")                
                return;                
            else
                target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        else
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);        
        }    
        transform.position = Vector2.MoveTowards(transform.position, target, pSpeed * Time.deltaTime);
}

bumping for more people to see

First of all you should not have two times “else” as second else is unreachable and idk how C# is not giving you an error there but oh well.
I cannot exactly see what is your problem but i recommend you to use Debug.DrawLine and draw a line from the raycast start position to the hit position. This way you will see how it behaves and i cannot see you checking if it hit something. So i recommend you to Debug.Log it too see what is hit with your raycast. You are not hitting object on “Obstacle” layer for sure.