Moving Object by mouse drag on x position only

I’m the beginner.I want to move object by mouse drag on x position only. Firstly, I try the sample code of mouse click. But the object move when click on anywhere . I want to move the object when click and drag on this object in x position only.When I use Raycast, it doesn’t work.I use the sprite object.Please help me.Thanks in advance.Following is my code.

function Update () {	
 
  if (Input.GetMouseButtonDown(0)) {  		
 		
     var ray : Ray = amera.main.ScreenPointToRay(Input.mousePosition);
     if (Physics.Raycast (ray)) {			
       var speed : Vector3 = Vector3 (3, 0, 0);
       rigidbody.MovePosition(rigidbody.position + speed * Time.deltaTime);
       Debug.Log("On Object");
 				
     }

  }
 
}

Got this from on here, credit to the original poster

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshCollider))]

public class GizmosController : MonoBehaviour 
{
	
	private Vector3 screenPoint;
	private Vector3 offset;
	public bool IsDragable = true;
	
	void OnMouseDown()
	{
		if(IsDragable)	// Only do if IsDraggable == true
		{
			screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
		
			offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
		}
	}
	
	void OnMouseDrag()
	{
		if(IsDragable)	// Only do if IsDraggable == true
		{
			Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z); // hardcode the y and z for your use
			
			Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
			transform.position = curPosition;
		}
	}
	
}

Should be easy enough to only alter the x position by hard coding the y and z.

I added the bool IsDragable you can get rid of that if you want but it’s set to true so shouldn’t affect anything.

Just place this script on the object you want to drag.

EDIT:

This is the post I got it from drag-gameobject-with-mouse