11

I'm trying to move a simple Object in Unity but I get the following error message:

cannot modify the return value of unityengine.transform.position because itar is not variable

Here is my code:

using UnityEngine;
using System.Collections;

public class walk : MonoBehaviour {
    // Use this for initialization
    void Start () {

    }

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

        float movespeed = 0.0f;
        movespeed++;
        transform.position.x  = transform.position.x + movespeed;

    }
}
Lex Li
  • 60,503
  • 9
  • 116
  • 147
Nawaf
  • 540
  • 1
  • 5
  • 14
  • 1
    It appears the X property of position is not mutable, can you assign a new Position value instead? eg `transform.position = new Position(transform.position.x + movespeed, transfrom.position.y);` – James Mar 17 '14 at 23:48
  • Error CS0246: The type or namespace name 'Position' could not be found (are you missing a using directive or an assembly reference?) (CS0246) (Assembly-CSharp) – Nawaf Mar 17 '14 at 23:58
  • All such questions should use `unity3d` tag. The tag `unity` is for a completely different thing. Please learn the tags before using them. – Lex Li Mar 18 '14 at 02:32

2 Answers2

26

You can't assign the x value on position directly as it's a value type returned from a property getter. (See: Cannot modify the return value error c#)

Instead, you need to assign a new Vector3 value:

transform.position = new Vector3(transform.position.x + movespeed, transform.position.y);

Or if you're keeping most of the coordinate values the same, you can use the Translate method instead to move relatively:

transform.Translate(movespeed, 0, 0)
Community
  • 1
  • 1
Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
  • it is work ok , but there are another problem , because the object is Directly Disappear after i press Play Game . – Nawaf Mar 18 '14 at 20:05
  • @Nawaf your computer is too fast! Multiply your movespeed by `Time.deltaTime` to keep it uniform on all CPU speeds. – Dr-Bracket Oct 26 '20 at 19:20
2

A slight improvement over Chris' answer:

transform.position = new Vector2(transform.position.x + movespeed * Time.deltaTime, transform.position.y);

Time.deltaTime the amount of time it's been between your two frames - This multiplication means no matter how fast or slow the player's computer is, the speed will be the same.

Dr-Bracket
  • 4,299
  • 3
  • 20
  • 28