Targeting script not finding a target 2D Mode

Hello, I am trying to get it so that when you click on a enemy sprite component with the tag “Enemy” it selects it as a target. I have tried several different methods, but I dont have the coding knowledge yet to figure it out. I have found this script on here but when I click on an enemy (It is tagged as Enemy) nothing happens and nothing is selected. Could anyone tell me why this is happening and how to fix it please?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
	
	public Transform selectedTarget;
	
	void Update(){
		if (Input.GetMouseButtonDown(0)){ // when button clicked...
			RaycastHit hit; // cast a ray from mouse pointer:
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			// if enemy hit...
			if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Enemy")){
				DeselectTarget(); // deselect previous target (if any)...
				selectedTarget = hit.transform; // set the new one...
				SelectTarget(); // and select it
			}
		}
	}
	
	private void SelectTarget(){
		selectedTarget.renderer.material.color = Color.red;
		Debug.Log ("Enemy Targeted");
	}
	
	private void DeselectTarget(){
		if (selectedTarget){ // if any guy selected, deselect it
			selectedTarget.renderer.material.color = Color.blue;
			selectedTarget = null;
		}
	}
}

You will not be able to use a 3D raycast in a 2D situation. Here is a bit of a rewrite to the code you are posting so that it will detect 2D colliders. I’m assuming your 2D objects are Sprites, so I’ve changed the way the color is changed. If they are not sprites, you can uncomment the lines for the original way these objects were colored.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
	
	private Transform selectedTarget = null;
	
	void Update(){
		if (Input.GetMouseButtonDown(0)){ // when button clicked...
			Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			Debug.Log (pos);
			RaycastHit2D hit; // cast a ray from mouse pointer:
			hit = Physics2D.Raycast (pos, Vector3.zero);

			if (hit != null && hit.transform != null && hit.transform.CompareTag("Enemy")) {
				DeselectTarget(); // deselect previous target (if any)...
				selectedTarget = hit.transform; // set the new one...
				SelectTarget(); // and select it
			}
		}
	}
	
	private void SelectTarget(){
		selectedTarget.GetComponent<SpriteRenderer>().color = Color.red;
		// selectedTarget.renderer.material.color = Color.red;
		Debug.Log ("Enemy Targeted");
	}
	
	private void DeselectTarget(){
		if (selectedTarget != null){ // if any guy selected, deselect it
			selectedTarget.GetComponent<SpriteRenderer>().color = Color.blue;
			//selectedTarget.renderer.material.color = Color.blue;
			selectedTarget = null;
		}
	}
}