# I want to clamp each instance of the same prefab to the y axis only

I instantiated the prefab "paddle" twice then I tried clamping it to the y-axis only; using Mathf.Clamp, however, the min and max values end up being applied to both instances of "paddle" and hence they can move in the x-axis

ok so I'm trying to make a 2d mobile pong game, I have a prefab "paddle" which are the rackets/bats which the balls collide with.

I instantiated the same prefab twice one on each side of the screen :

Paddle paddle1 = Instantiate(Paddle) as Paddle;


Now i want each of the paddles to only be able to move in the y axis (UP And DOWN).

So I tried clamping them with:

var poss = transform.position;
poss.x =  Mathf.Clamp(transform.position.x, -1.0f, 1.0f);
transform.position = poss;


However, this caused the left paddle to still be able to move to the right and the right paddle to be able to the left( I don't want them to move in the axis at all).

This is the file GameManager.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager: MonoBehaviour
{
public Ball Ball;

public static Vector2 topRight;
public static Vector2 bottomLeft;

// Start is called before the first frame update
void Start()
{
bottomLeft = Camera.main.ScreenToWorldPoint(new Vector2 (0,0));
topRight = Camera.main.ScreenToWorldPoint(new Vector2
(Screen.width,Screen.height));

Instantiate(Ball);

}

void Update()
{

}

}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

{
Rigidbody2D rb;
float directionY;
float speed;
float height;

float distance;
string input;
bool isRight;

// Start is called before the first frame update
void Start()
{
height = transform.localScale.y;
speed=5f;
}

{
Vector2 pos = Vector2.zero;

{
//Place paddle on the right of the screen
pos = new Vector2(GameManager.topRight.x, 0);
pos -= Vector2.right * transform.localScale.x; //Move a bit to the left
}
else
{
//Place paddle on the left of the screen
pos = new Vector2(GameManager.bottomLeft.x, 0);
pos += Vector2.right * transform.localScale.x; //Move a bit to the right
}

transform.position = pos;
}

void Update()
{
var poss = transform.position;
poss.x =  Mathf.Clamp(transform.position.x, -8.0f, 8.0f);
transform.position = poss;
}
}


I expect each paddle to not be able to move in the x axis. Only in the y axis

c# unity3d mobile

TL;DR: you are updating the x position value while you want to update the y value.

        var poss = transform.position;

This code will let your paddle moving on x (left / right) from -8.0 to 8.0 values. In Unity, by default, left/right axis is x, up/down is y, and forward/back is z. If you want your paddle to only move on Y when you press up and down arrow, you just have to only update the Y value of their transform.position and clamp it to the min / max values you need while forcing the default x and z values that you need.