You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#:持钥碰撞栅栏销毁障碍报错排查与功能实现

Unity钥匙栅栏功能编译错误修复方案

问题描述

我正在开发一款Unity游戏,设置了玩家需获取钥匙才能穿过的栅栏:栅栏设为Trigger可穿过,但后方存在障碍物体。需求为当玩家持有钥匙并碰撞栅栏时,销毁所有带“fence barrier”Tag的障碍物体。目前代码出现编译报错:

  • Assets\playerController.cs(18,17): error CS1002: ; expected
  • Assets\playerController.cs(18,30): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
    添加分号后仍报错:
  • Assets\playerController.cs(16,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration

错误代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

namespace scripting // <-- This is a namespace
{
    public class playerController : MonoBehaviour
    {
        public float moveSpeed = 1f;
        public float collisionOffset = 0.05f;
        public ContactFilter2D movementFilter;
        public bool gotKey = false;

        public List<string> items;
        public GameObject[];

        Vector2 movementInput;
        Rigidbody2D rb;
        List<RaycastHit2D> castCollisions = new List<RaycastHit2D> ();

        // Start is called before the first frame update
        void Start()
        {
            items = new List<string>();

            rb = GetComponent<Rigidbody2D>();
        }

        private void FixedUpdate()
        {
            if(movementInput != Vector2.zero)
            {
                int count = rb.Cast(
                    movementInput,
                    movementFilter,
                    castCollisions,
                    moveSpeed * Time.fixedDeltaTime + collisionOffset);
                if(count == 0)
                {
                    rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
                }
            }
        }
        void OnMove(InputValue movementValue)
        {
            movementInput = movementValue.Get<Vector2>();
        }
        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("collectable"))
            {
                string itemType = collision.gameObject.GetComponent<collectable_script>().itemType;
                print("we have collected a " + itemType);
                items.Add(itemType);
                print("Inventory length:" + items.Count);
                Destroy(collision.gameObject);
            }
            else if (collision.CompareTag("key"))
            {
                print("colliding!");
                gotKey = true;
                if (gotKey == true)
                {
                    print("yay!");
                }
                Destroy(collision.gameObject);
            }
            else if (collision.CompareTag("fence"))
            {
                print("fence!");
                if (gotKey == true)
                {
                    GameObject[] fencestop = GameObjects.FindGameObjectsWithTag("fence barrier");
                    foreach (GameObject item in fencestop)
                    {
                        Destroy(item);
                    }
                }
            }
        }
    }
}

错误分析与修复步骤

  1. 无效数组声明:第18行public GameObject[];是错误的C#语法——声明数组变量必须指定变量名,且这段代码未使用该变量,直接删除该行即可解决前两个编译错误。
  2. API拼写错误:第72行GameObjects.FindGameObjectsWithTag拼写有误,Unity正确API为GameObject.FindGameObjectsWithTag(注意是单数GameObject),修正后可解决剩余编译错误。

修复后的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

namespace scripting
{
    public class playerController : MonoBehaviour
    {
        public float moveSpeed = 1f;
        public float collisionOffset = 0.05f;
        public ContactFilter2D movementFilter;
        public bool gotKey = false;

        public List<string> items;

        Vector2 movementInput;
        Rigidbody2D rb;
        List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();

        void Start()
        {
            items = new List<string>();
            rb = GetComponent<Rigidbody2D>();
        }

        private void FixedUpdate()
        {
            if (movementInput != Vector2.zero)
            {
                int count = rb.Cast(
                    movementInput,
                    movementFilter,
                    castCollisions,
                    moveSpeed * Time.fixedDeltaTime + collisionOffset);
                if (count == 0)
                {
                    rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
                }
            }
        }

        void OnMove(InputValue movementValue)
        {
            movementInput = movementValue.Get<Vector2>();
        }

        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("collectable"))
            {
                string itemType = collision.gameObject.GetComponent<collectable_script>().itemType;
                print("we have collected a " + itemType);
                items.Add(itemType);
                print("Inventory length:" + items.Count);
                Destroy(collision.gameObject);
            }
            else if (collision.CompareTag("key"))
            {
                print("colliding!");
                gotKey = true;
                if (gotKey)
                {
                    print("yay!");
                }
                Destroy(collision.gameObject);
            }
            else if (collision.CompareTag("fence"))
            {
                print("fence!");
                if (gotKey)
                {
                    GameObject[] fencestop = GameObject.FindGameObjectsWithTag("fence barrier");
                    foreach (GameObject item in fencestop)
                    {
                        Destroy(item);
                    }
                }
            }
        }
    }
}

修复效果

修复后代码可正常编译,玩家获取钥匙后碰撞栅栏时,所有带有“fence barrier”标签的障碍物体会被销毁,符合需求逻辑。

内容的提问来源于stack exchange,提问作者maxjj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:45