Can anyone tell me why this code isn't working?

I’m trying to make a simple pong game using a tutorial I found online. The person in the tutorial is using javascript, but i’m trying to follow along using C#.

Here is the script i’m using:

using UnityEngine;
using System.Collections;

public class playerScript : MonoBehaviour {

	public KeyCode moveUp;
	public KeyCode moveDown;

	public float speed = 10f;

	// Update is called once per frame
	void Update () 
	{
		Vector2 v = rigidbody2D.velocity;
		if(Input.GetKey(moveUp))
		{
			v.y = speed;
		}
		else if(Input.GetKey (moveDown))
		{
			v.y = speed * -1;
		}
		else
		{
			v.y = 0;
		}
	
	}
}

I had an issue compiling at first, and had to make my Vector2 into a variable for some reason. I don’t know why, but I guess you need a temporary value for rigibody2D.velocity. But the character won’t move at all if I hit W or S, which are the keys the public variables are assigned to. Am I missing something due to a c# coding issue?

It seems logical. Two keys created, a speed created. Vector2 v is initialized as the rigidbody’s velocity. If I hold w it should move in a positive 10 direction. Reverse for the S key. I’m not understanding the issue.

Vector2 is a struct. This means it is passed by value. This means that you need to reassign it back.

Add this line after all of your if/else clauses to reassign the variable back to velocity.

rigidbody2D.velocity = v;