Cannot modify return value of..... consider storing the value in a temporary variable ERROR

I’m following a tutorial that you can view at

. I’m using the moving platform script here, but it’s written in Javascript, while I want to use C#. So here’s the C# adaptation I made… and this is the error:

Assets/Enemymovement.cs(31,45): error CS1612: Cannot modify a value type return value of `UnityEngine.Rigidbody2D.velocity’. Consider storing the value in a temporary variable

Script:

using UnityEngine;
using System.Collections;

public class Enemymovement : MonoBehaviour {

public bool what = false;
public int speed = 0;

public int whatway = 0;

public int timer = 0;

public int maxTimer = 50;

// Update is called once per frame
void Update () {

if (what == false) {

if (whatway == 0){
rigidbody2D.velocity.x = -speed;
}
if (whatway == 1){
rigidbody2D.velocity.y = -speed;
}
}
if (what == true) {

if (whatway == 0){
rigidbody2D.velocity.x = speed;
} if (whatway == 1){
rigidbody2D.velocity.y = speed;
}
}
timer += 1;
if (timer >= maxTimer) {
timer = 0;

if (what == false) {
what = true;
timer = 0;
return;
} else if (what == true) {
what = false;
timer = 0;
return;
}

}

}
}

Anyone know how to fix this? I’ve tried switching ‘rigidbody2D’ to ‘Rigidbody2D’ but then I just get another error.

rigidbody2d.velocity is a Vector2 type, you can’t just type rigidbody2d.velocity.x = 20 for example. Try this instead:

Vector2 newVelocity = rigidbody2d.velocity; //Create temporary variable
newVelocity.x -= speed; //Assign a value to the temporary variable
rigidbody2d.velocity = newVelocity. //Assign temporary variable back to rigidbody2d.velocity.

So first make a temporarily variable of the type you want to store (in this case a Vector2), give the variable a value, and then assign the variable back to the original. This same principle works for any variable, if you try to set transform.position.x = 20 you get the same error as you’re getting now. I hope I’m making any sense, if not I will try to explain it some other way.

Why not one line?

rigidbody2d.velocity = new Vector2(rigidbody2d.velocity.x - speed, rigidbody2d.velocity.y);

That’s even better as long as the point gets across :slight_smile: