Your issue is with: GetComponent().Rigidbody2D() as that is not how you use GetComponent, the error you are seeing is probably because GetComponent requires a parameter or a specified type. The JS and C# GetComponent work a little different. You probably mean to do:
void Update ()
{
float xVel = GetComponent<Rigidbody2D>().velocity.x;
if( xVel < 18 && xVel > -18 && xVel !=0){
if(xVel > 0){
GetComponent<Rigidbody2D>().velocity.x = 20;
}else{
GetComponent<Rigidbody2D>().velocity.x = -20;
}
}
}
Also in C#, I don't think you can modify the velocity directly, due to the property wrappers around it. Instead you have to manually update the velocity to a new Vector2. If you only want to set the x value, pass in the existing y value.
I would write it something like this:
private Rigidbody2D _rigidBody;
void Start()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
void Update ()
{
float xVel = _rigidBody.velocity.x;
if( xVel < 18 && xVel > -18 && xVel !=0){
if(xVel > 0){
_rigidBody.velocity = new Vector2(20, _rigidBody.velocity.y);
}else{
_rigidBody.velocity = new Vector2(-20, _rigidBody.velocity.y);
}
}
}
Though I'd change that magic 18 in to a variable too but I can't make a guess here as to what it represents!
xVelactually?