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

Unity收集4枚硬币后无法用SetActive(false)隐藏门的问题求助

解决Roll-A-Ball中收集硬币后门自动消失的问题

问题根源

你当前代码有两个关键问题:

  1. gameObject.SetActive(false)操作的是当前脚本挂载的玩家对象,不是门,等于把玩家自己禁用了,完全没处理门的逻辑
  2. 依赖OnTriggerEnter触发门的逻辑,必须碰门才会执行,不符合你收集满硬币立刻消失的需求

正确实现方案

我们需要在收集硬币后立即检查数量,一旦达到4枚,就找到所有带Door标签的门部件并禁用,同时加个标记避免重复执行:

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

public class PlayerControls : MonoBehaviour
{
    Rigidbody rb;
    [SerializeField] float movementSpeed = 5f;
    [SerializeField] float jumpForce = 5f;
    int coins = 0;
    // 标记门是否已经打开,避免重复执行查找操作
    bool doorHasOpened = false;

    void Start()
    {
        rb = GetComponent<Rigidbody>(); 
    }

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        rb.velocity = new Vector3(horizontalInput * movementSpeed, rb.velocity.y, verticalInput * movementSpeed);

        if (Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Coin"))
        {
            Destroy(other.gameObject);
            coins++;
            Debug.Log("Coins: " + coins);
            
            // 收集硬币后立即检查数量,且门还没打开过
            if (coins == 4 && !doorHasOpened)
            {
                // 找到所有带Door标签的对象
                GameObject[] doorParts = GameObject.FindGameObjectsWithTag("Door");
                // 遍历禁用每个门部件
                foreach (var doorPart in doorParts)
                {
                    doorPart.SetActive(false);
                }
                // 标记门已打开,避免重复执行
                doorHasOpened = true;
                Debug.Log("门已消失");
            }
        }
    }
}

额外优化建议

如果门的部件较多,FindGameObjectsWithTag在运行时查找效率不算最高,你也可以在Start里提前获取所有门部件,后续直接使用:

GameObject[] doorParts;

void Start()
{
    rb = GetComponent<Rigidbody>();
    doorParts = GameObject.FindGameObjectsWithTag("Door");
}

这样后续遍历doorParts即可,不用每次收集硬币都重新查找。

另外,门分成四个部件的方案完全没问题,只要所有需要消失的部件都正确打上Door标签即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:42:08