detecting touch on gameObject

Hello,
I have 2 gameObjects called (right , left)
I need to execute some actions in case of touching one of them
but it does not detect any touch input , take a look of the below code :slight_smile:

public class player : MonoBehaviour {
	public float speed = 3;
	public GameObject left; //assigned via inspector
	public GameObject right; //assigned via inspector
	private Animator anim;
	// Use this for initialization
	void Start () {
		anim = gameObject.GetComponent<Animator> ();
	}
	
	// Update is called once per frame
	void Update () {
		Vector3 scale = transform.localScale;
		if (Input.touchCount > 0) {
			Touch t = Input.GetTouch(0);
			if (t.phase == TouchPhase.Began)
			{
				if (left.GetComponent<SpriteRenderer>().bounds.Contains(t.position))
				{
					anim.SetInteger ("walk", 1);
					transform.Translate (-speed * Time.deltaTime, 0, 0);
					scale.x = -1;
				}
				else if (right.GetComponent<SpriteRenderer>().bounds.Contains(t.position))
				{
					anim.SetInteger ("walk" , 1);
					transform.Translate(speed*Time.deltaTime,0,0);
					scale.x = 1;
				}
			}
			else if (t.phase == TouchPhase.Ended)
			{
				anim.SetInteger ("walk" , 0);
			}
		}

You should have a script component for each โ€œleftโ€ and โ€œrightโ€ gameObject.

Inside those scripts, use the OnMouseDown function and execute your code inside the function.

i.e.

void OnMouseDown(){
anim.SetInteger ("walk", 1);
transform.Translate (-speed * Time.deltaTime, 0, 0);
scale.x = -1;
}

to execute code when the user lifts their finger off the screen, use OnMouseUp instead.