Unity安卓滑动控制系统报错CS0131:赋值左侧需为变量、属性或索引器
搞定Unity安卓滑动控制的CS0131错误
嘿,这个Error CS0131的坑我之前做触屏交互的时候也踩过!问题出在你写的连续赋值语句上,而且逻辑也搞错了——你本来想计算滑动的差值,结果写成了给只读属性赋值,编译器当然要报错啦。
先看你出错的核心代码行:
swipeDelta = Input.touches[0].position = startTouch;
这里有两个关键问题:
Input.touches[0].position是只读属性,你不能给它赋值(也就是不能写xxx.position = 某个值);- 你想要的是计算当前触摸位置和起始触摸位置的差值,而不是把
startTouch的值同时塞给position和swipeDelta。
另外你没写完的鼠标部分代码,也要注意正确计算差值,而不是赋值。
给你修正后的完整代码片段,顺便补了一些逻辑上的细节(比如触摸开始时的初始化):
bool isDragging = false; // 这里改成了更规范的拼写,你也可以保持原来的isDraging写法 Vector2 startTouch, swipeDelta = Vector2.zero; // 先处理触摸/鼠标按下的初始化逻辑 if (Input.GetMouseButtonDown(0)) { isDragging = true; startTouch = (Vector2)Input.mousePosition; } // 处理触屏的开始触摸事件 else if (Input.touches.Length > 0 && Input.touches[0].phase == TouchPhase.Began) { isDragging = true; startTouch = Input.touches[0].position; } // 滑动中的逻辑 if (isDragging) { if (Input.touches.Length > 0) { // 计算当前触摸位置与起始位置的差值,这才是swipeDelta的正确赋值方式 swipeDelta = Input.touches[0].position - startTouch; } else if(Input.GetMouseButton(0)) { // 鼠标模拟触摸,同样计算差值,把屏幕坐标转换成Vector2 swipeDelta = (Vector2)Input.mousePosition - startTouch; } // 触摸/鼠标松开时重置状态 else { swipeDelta = Vector2.zero; isDragging = false; } }
最后提个小建议:记得在触摸结束(TouchPhase.Ended)或者鼠标松开(Input.GetMouseButtonUp(0))的时候重置isDragging和swipeDelta,不然滑动状态会一直保留,影响后续交互~
内容的提问来源于stack exchange,提问作者SeeSharp
相关产品推荐
相关产品推荐

