Unity脚本报错:Operator '||'无法应用于string类型操作数
问题分析与修复方案
你的代码存在两个关键错误:
- 误用赋值运算符
=而非比较运算符==,这会把PLAYER_JAB的值直接赋给currentState,而非判断两者是否相等。 ||逻辑或运算符要求两侧必须是布尔表达式(真/假结果),你直接将两个字符串用||连接,不符合C#语法规则。
修复方案1:直接修正条件表达式
这是最直观的修改方式,分别对每个攻击状态做相等判断,再用||连接布尔结果:
void Update() { // ... //No Moving while Attacking if (currentState == PLAYER_JAB || currentState == PLAYER_KICK) { speed = 0; } }
修复方案2:用集合简化判断(适合扩展更多状态)
如果后续需要添加更多攻击状态,用HashSet<string>存储所有攻击状态,判断逻辑会更简洁易维护:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed; private string currentState; const string PLAYER_JAB = "Jab"; const string PLAYER_KICK = "Kick"; private HashSet<string> attackStates; void Awake() { attackStates = new HashSet<string> { PLAYER_JAB, PLAYER_KICK }; } // ... void Update() { // ... //No Moving while Attacking if (attackStates.Contains(currentState)) { speed = 0; } } }
修复方案3:用枚举替代字符串(类型安全的规范方案)
字符串状态容易出现拼写错误,改用枚举能让代码更健壮、可读性更强:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed; private PlayerState currentState; enum PlayerState { Idle, Jab, Kick // 可按需添加更多状态 } // ... void Update() { // ... //No Moving while Attacking if (currentState == PlayerState.Jab || currentState == PlayerState.Kick) { speed = 0; } } }
内容的提问来源于stack exchange,提问作者KingBarou13
相关产品推荐
相关产品推荐

