Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move simple Object in Unity 2D

Tags:

c#

unity3d

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;

    }
}
like image 835
Nawaf Avatar asked Mar 17 '14 23:03

Nawaf


2 Answers

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.

like image 150
Dr-Bracket Avatar answered Sep 25 '22 07:09

Dr-Bracket


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)
like image 21
Chris Sinclair Avatar answered Sep 21 '22 07:09

Chris Sinclair