为什么我在Unity3D中出现此错误

本文关键字:错误 Unity3D 为什么 | 更新日期: 2023-09-27 18:19:33

这是我得到的错误:

Assets/Scripts/CameraScript.cs(60,39):错误CS1612:无法修改"UnityEngine.Transform.position"的值类型返回值。请考虑将该值存储在临时变量中

这是我的代码:

void  Start (){
        thisTransform = transform;
        // Disable screen dimming
        Screen.sleepTimeout = 0;
    }
    void  Update (){
        //Reset playerscore 
        playerScore = settings.playerScore;
        //Smooth follow player character
        if  (target.position.y > thisTransform.position.y)  {           
            thisTransform.position.y = Mathf.SmoothDamp( thisTransform.position.y, 
                                                        target.position.y, ref velocity.y, smoothTime);
        }
    }

为什么我在Unity3D中出现此错误

不能单独设置thisTransform.position.y值。改为设置thisTransform.position

例如:

if  (target.position.y > thisTransform.position.y)  {           
  thisTransform.position = new Vector3(thisTransform.position.x, 
                                       Mathf.SmoothDamp( thisTransform.position.y, target.position.y, ref velocity.y, smoothTime), 
                                       thisTransform.position.z);
}

Transform.position.y在C#中是只读的,因此为了修改它,您需要首先将Transform.position的值存储到一个临时变量中,更改该变量的值,然后将其分配回Transform.position:

Vector3 temp = thisTransform.position;
temp.y = Mathf.SmoothDamp( temp.y, target.position.y, ref velocity.y, smoothTime);
thisTransform.position = temp;