Enemy follow player

Hi all im making a 2D platform game, i have this script where the enemy follow the player at certain distance, but i realise that the enemy can cross the walls,c an some helpme ?

void Update () 
	{
		
		if (life <= 0)
		{
			
			Death();
		}

		range = Vector2.Distance(transform.position, player.position);
		Debug.DrawLine(player.position, enemy.position, Color.red); 

		if(range < distance)
		{
			
			transform.position = Vector2.MoveTowards(transform.position, player.position, moveSpeed * Time.deltaTime);
			
			anim.Play("Walk");
		}

		if(range > distance)
		{
			anim.Play("Idle");
		}
		

		 if(player.position.x > transform.position.x){
    	 //face right
    		 transform.localScale = new Vector3(1,1,1);
    	 }else if(player.position.x < transform.position.x){
     	//face left
    		 transform.localScale = new Vector3(-1,1,1);
     	}
	
		
		
	}

If you want the object/enemy to collide with walls then you must use physics commands to move it. You’ll probably want to use RigidBody.MovePosition or AddForce. MovePosition may still force the object to appear within colliders, that all depends on if you’re doing anything to tell it to change direction when it hits something. AddForce will cause it to run into colliders and bounce off of them.

Ultimately you should watch the tutorial on NavMesh and learn how to use it. It can be applied to a 2D environment, you just need to use 3D colliders.