How to detect a touch on a 2D sprite

Hi,
I realize there’s a lot of questions for this topic already but none of them really fixed this for me.
Maybe I’m just doing it completely wrong, I am very much a noob with unity.

Anyway, I have a 2D sprite on which I have added an Edge collider 2D. I’m trying to detect when I touch it, on my touch device.

I tried to follow another post I found here, but it never registers a touch.
Here’s the code I have so far.

    private Collider2D collider;

    // Use this for initialization
    void Start()
    {
		collider = GetComponent<Collider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckForTouch();
    }

    bool CheckForTouch()
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {

			var wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
			var touchPosition = new Vector2(wp.x, wp.y);

			if (collider == Physics2D.OverlapPoint(touchPosition)){
				Debug.Log("HIT!");
			}
			else{
				 Debug.Log("MISS");
			}
        }
		return false;
    }

Maybe the edge collider isn’t working (You have to touch the edge?), try using a polygon colider

@Nicoolai
If you are going for a UI perspective, you can use the Button component and use the On Click () function to state what you would like it to do (NOTE: The void function you are calling via the button must be a public void ).

Otherwise, if you are using sprites and want to recieve input when target sprite is touched (from what I am seeing that is what you want your code to do), you may want to look into void OnMouseDown() function and do something like this.

void OnMouseDown() { Debug.Log("HIT!"); }

More can be read about OnMouseDown() here. You can also check OnMouseUp() so the target function is only called when you release your mouse button

If I did not answer your question the way you were looking for, just reply asking whatever I missed :slight_smile:

Hope this helped!