Controlling 2 different objects with 1 script

Im making a Pong game and our teacher wants us to use the same script for both the paddles and my question is how do i go about doing that?

Here’s my code for one of the paddles, which works great. Both are the same just different KeyCode.X, i just have to take the other one and put them both in the same script, but they each should control different paddles.

if (Input.GetKey (KeyCode.W)) {
rigidbody2D.velocity = new Vector3 (0, +10, 0);
transform.position = new Vector3 (-9, transform.position.y, transform.position.z);
}

if (Input.GetKey (KeyCode.S)) {
rigidbody2D.velocity = new Vector3 (0, -10, 0);
transform.position = new Vector3 (-9, transform.position.y, transform.position.z);
}
if (!Input.GetKey (KeyCode.W) && !Input.GetKey (KeyCode.S)) {
rigidbody2D.velocity = new Vector3 (0, 0, 0);
}

Make the used KeyCode a public variable.
Then you can assign the used key in the inspector.

// The up key
public KeyCode keyUp;

// The down key
public KeyCode keyDown;

To use the variable, just replace the content of the if’s with:

if (Input.GetKey(keyUp))
{
    // Code for upward movement
}

if (Input.GetKey(keyDown))
{
    // Code for downward movement
}

With that, you would have a script that can be used as often as you want.
Don’t forget to assign the keys in the inspector, else it won’t work. :wink:

Greetings
Chillersanim

you could also reference the paddles as two different game objects like for example:

public GameObject paddle1;

public GameObject paddle2;

		void update()
		{
		if(Input.GetKeyDown(KeyCode.S))
		{
			paddle1.rigidbody2D.velocity = new Vector3 (0, +10, 0);
			paddle1.transform.position = new Vector3 (-9, paddle1.transform.position.y, paddle1.transform.position.z);
		}
		else
		{
			paddle1.rigidbody2D.velocity = new Vector3 (0, 0, 0); 
		}
		if(Input.GetKeyDown(KeyCode.W))
		{
			paddle2.rigidbody2D.velocity = new Vector3 (0, +10, 0);
			paddle2.transform.position = new Vector3 (-9, paddle2.transform.position.y, paddle2.transform.position.z);
		}
		else
		{
			paddle2.rigidbody2D.velocity = new Vector3 (0, 0, 0); 
		}
		}			

after that you assign them into the inspector and it should be ready.