在Unity 2D中移动简单对象

时间:2014-03-17 23:43:31

标签: c# unity3d

我正在尝试在Unity中移动一个简单的Object但是我收到以下错误消息:

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

这是我的代码:

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;

    }
}

2 个答案:

答案 0 :(得分:23)

您无法直接在x分配position值,因为它是从属性获取器返回的值类型。 (见:Cannot modify the return value error c#

相反,您需要指定一个新的Vector3值:

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

或者,如果您保持大部分坐标值相同,则可以使用Translate方法相对移动:

transform.Translate(movespeed, 0, 0)

答案 1 :(得分:1)

对克里斯的回答略有改善:

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

Time.deltaTime介于两帧之间的时间-这种乘法意味着无论播放器计算机的速度有多快,速度都将相同。

相关问题