- Home /
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.
Answer by Kiwasi · Sep 24, 2014 at 10:25 PM
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;
Thanks it worked. Not sure I fully understand WHY i have to do this, but as long as it works I know I can replicate it in future games.
Google pass by value and pass by reference.
When you pass a class you pass the pointer to the class. This means that any changes you make to the class will be changed on the original. There is only one copy.
When you pass a struct you pass a copy of the struct. Every value contained is duplicated in your new location. This is more efficient for small data structures. But it means any changes you make on a copy are not passed back to the original.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
2D top down dash code 1 Answer
Create custom constructors for certain Value types/Objects (Vector3, Transform, etc...) 2 Answers