Restricting movement with Mathf.Clamp

Hi, I’m new to Unity and I’m trying to clone the Pong game right now but I’m stuck with movement restriction. I found one example that worked, but it worked in JS and I’m trying to learn C# so don’t want to use any JS scripts now. The problem is that I want to restrict vertical movement of the paddle to -4.1f min and 4.1f max.

using UnityEngine;
using System.Collections;

public class RacketController : MonoBehaviour {
	
	public float speed = 5.0f;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		float yMove = Input.GetAxis("Vertical") * Time.deltaTime * speed;
		transform.Translate(0f ,yMove, 0f);
		transform.position.y = Mathf.Clamp(transform.position.y, -4.1f, 4.1f);
	}
}

The similar code worked in JS but in C# the compiler returns an error on line where I try to clamp transform.position.y. I tried a lot of different solutions found on Unity Answers or in forums but I can’t get it (or those examples won’t work with my situation).

In C#, unlike UnityScript, the individual elements in a Transform’s position property are not accessible directly.
Instead, you need to define a new vector and assign the whole of it, so for instance in your example you would do something like:

void Update()
{
	float yMove = Input.GetAxis("Vertical") * Time.deltaTime * speed;
	transform.Translate(0f, yMove, 0f);

    // initially, the temporary vector should equal the player's position
	Vector3 clampedPosition = transform.position;
    // Now we can manipulte it to clamp the y element
	clampedPosition.y = Mathf.Clamp(clampedPosition.y, -4.1f, 4.1f);
    // re-assigning the transform's position will clamp it
	transform.position = clampedPosition;
}

In C# you cannot directly assign transform.position vector. As it is read only.

Change

transform.position.y = Mathf.Clamp(transform.position.y, -4.1f, 4.1f);

to

transform.position = new Vector3 (transform.position.x, Mathf.Clamp(transform.position.y, -4.1f, 4.1f), transform.position.z);

Building upon Priyanshu’s Answer, the following was what i needed to limit my top-down perspective camera movement for panning.

void ClampTransform(Transform t, Vector3 origin, float distanceX, float distanceZ)
{
    var z = Mathf.Clamp(t.position.z, origin.z - distanceZ, origin.z + distanceZ);
    var x = Mathf.Clamp(t.position.x, origin.x - distanceX, origin.x + distanceX);
    t.position = new Vector3(x, t.position.y, z);
}

you can write Simple if condition also like this below

if(transform.position.y<=-4.1f)
{
transform.position = new Vector3( transform.position.x, -4.1f, transform.position.z);
}

if(transform.position.y>=4.1f)
{
transform.position = new Vector3( transform.position.x, 4.1f, transform.position.z);
}