Unity C#代码报错CS1014:'A get or set accessor expected'的含义及修复方案咨询
Hey, let's break down your errors and fix the code step by step.
错误原因解析
First, those two CS1014 errors mean exactly what the compiler says: the C# parser expects valid syntax for a property's get or set accessor, but your code doesn't follow the rules for property definitions.
The problem is this line:
public float AttackRange { get => attackRange; 0.5f => attackRange = 0.5f; }
Your set accessor logic is completely invalid—0.5f => attackRange = 0.5f isn't how you define a setter. It looks like you might have been trying to set a default value here, but you already assigned 0.5f to the attackRange field directly, so that's unnecessary. Property setters should use the value keyword to accept incoming values, or you can omit the setter entirely if you don't want external code modifying the range.
On top of that, your code has a few other small bugs that will prevent it from compiling:
attackPoint.postionis a typo—should beattackPoint.position- You're trying to iterate over
hitEnemiesbut never declared or assigned this variable Debug.lotis a typo—correct isDebug.Log(note the capital L)
Fix Steps
Fix the
AttackRangeproperty syntax
If you just wantAttackRangeto be a wrapper for theattackRangefield, use this valid expression-body syntax:public float AttackRange { get => attackRange; set => attackRange = value; }If you don't need external code to modify the range, you can simplify it to a read-only property:
public float AttackRange => attackRange;Properly handle collision detection results
Assign the return value ofPhysics2D.OverlapCircleAllto a variable before iterating over it:Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, AttackRange, enemyLayers);Fix all typos
CorrectpostiontopositionandlottoLog.
Full Fixed Code
using System.Collections.Generic; using UnityEngine; public class PlayerCombat : MonoBehaviour // 类名建议用大驼峰命名,符合Unity规范 { public Animator animator; public Transform attackPoint; public float attackRange = 0.5f; public LayerMask enemyLayers; // 修正后的属性,作为字段的包装器 public float AttackRange { get => attackRange; set => attackRange = value; } void Update() { if (Input.GetKeyDown(KeyCode.Q)) { Attack(); } } void Attack() { animator.SetTrigger("Attack"); // 获取所有被攻击范围内的敌人碰撞体 Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, AttackRange, enemyLayers); foreach (Collider2D enemy in hitEnemies) { Debug.Log("Hit " + enemy.name); } } void OnDrawGizmosSelected() { if (attackPoint == null) return; Gizmos.DrawWireSphere(attackPoint.position, AttackRange); } }
Quick side note: Unity script class names follow PascalCase (like PlayerCombat instead of playercombat) to match the engine's API style, so it's a good habit to adopt for readability.
内容的提问来源于stack exchange,提问作者ottok07

