How to clamp Player to Camera Screen border

float xMin, xMax, yMin, yMax;
Camera cam;
void Start () {
cam = Camera.main;

    		xMin = cam.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;
    		xMax = cam.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
    		yMin = cam.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
    		yMax = cam.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;
    	}

    private void Movement4(){
    		float newX = transform.position.x + GetX();
    		float newPosX = Mathf.Clamp(newX, xMin, xMax);
    		transform.position = new Vector3(newPosX, 0, 0);
    		 
    	}
    	private float GetX(){return Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;}

I wanted an object to keep residing in the screen no matter where the camera’s position is so that I don’t have to rely on raw value (eg. Mathf.Clamp(newX, -10, 10))

I don’t know what’s the problem here

It worked in 2D mode but didn’t in 3D

When using the ViewportToWorldPoint() method your vector needs to have a Z vaule. From docs -

“Provide the function with a vector where the x-y components of the vector are the screen coordinates and the z component is the distance of the resulting plane from the camera.”

In short the z is how far away the camera is from the point in space you want to get. If you are making a 2D game, the z could be Mathf.Abs(transform.position.z - cam.position.z) (Mathf.Abs is to make the distance always be a positive number). This will only work if your camera has no rotation and is facing the player directly so their z axes align.

how does the object leave the bounds of the screen to begin with?
if your using collision and triggers there is a trigger for leaving a rigidbody. if you have a bounding box the size of the camera viewpoint you can detect when something exits.