Game Object Follow finger

I am making a game where I need the x touch to follow a gameobject so I can slide it from side to side. I am a beginner so I’m not sure what to do.

As a quick solution, use Input.mousePosition and Camera.main.ScreenPointToWorldPoint. You could also get individual touch positions with Input.touches.


FollowTouch.cs

using UnityEngine;

// Attach this component to the GameObject you want to follow the touch position.
public class FollowTouch : MonoBehaviour
{
	// every frame
	void Update ()
	{
		// if left-mouse-button is being held OR there is at least one touch
		if (Input.GetMouseButton(0) || Input.touchCount > 0)
		{
			// get mouse position in screen space
			// (if touch, gets average of all touches)
			Vector3 screenPos = Input.mousePosition;
			// set a distance from the camera
			screenPos.z = 10.0f;
			// convert mouse position to world space
			Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);

			// get current position of this GameObject
			Vector3 newPos = transform.position;
			// set x position to mouse world-space x position
			newPos.x = worldPos.x;
			// apply new position
			transform.position = newPos;
		}
	}
}

Tested with mouse. I have not tested with touches.

I am having the same issue the object is going to the left side