Search Unity

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

Discussion in 'Scripting' started by Shippety, Aug 30, 2014.

  1. Shippety

    Shippety

    Joined:
    May 9, 2014
    Posts:
    31
    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.
     
  2. willemsenzo

    willemsenzo

    Joined:
    Nov 15, 2012
    Posts:
    585
    rigidbody2d.velocity is a Vector2 type, you can't just type rigidbody2d.velocity.x = 20 for example. Try this instead:

    Code (csharp):
    1.  
    2. Vector2 newVelocity = rigidbody2d.velocity; //Create temporary variable
    3. newVelocity.x -= speed; //Assign a value to the temporary variable
    4. rigidbody2d.velocity = newVelocity. //Assign temporary variable back to rigidbody2d.velocity.
    5.  
    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.
     
  3. JAKJ

    JAKJ

    Joined:
    Aug 17, 2014
    Posts:
    185
    Why not one line?

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

    willemsenzo

    Joined:
    Nov 15, 2012
    Posts:
    585
    That's even better as long as the point gets across :)