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

Unity物体自动隐藏显示脚本问题求助:仅隐藏不显示

Unity物体隐藏后无法再次显示的问题解决

问题根源

当调用gameObject.SetActive(false)时,挂载在该物体上的所有脚本都会停止运行,Update()方法不再执行,导致后续的显示计时逻辑完全无法触发,这就是控制台只输出“hide”的原因。

解决方案

方案1:使用独立控制物体(推荐)

将控制脚本挂载在始终激活的物体上,通过引用目标物体来控制显隐,避免脚本随目标物体一同停止:

using UnityEngine;
using System.Collections;

public class ObjectVisibilityController : MonoBehaviour
{
    public GameObject targetObject; // 在Inspector面板拖入要控制的目标物体
    private readonly float _disappearDelay = 2f;
    private readonly float _appearDelay = 2f;

    void Start()
    {
        StartCoroutine(ToggleVisibilityLoop());
    }

    IEnumerator ToggleVisibilityLoop()
    {
        while (true)
        {
            yield return new WaitForSeconds(_disappearDelay);
            targetObject.SetActive(false);
            Debug.Log("hide");

            yield return new WaitForSeconds(_appearDelay);
            targetObject.SetActive(true);
            Debug.Log("show");
        }
    }
}

方案2:禁用Renderer替代SetActive(false)

如果必须将脚本挂载在目标物体上,可以通过禁用Renderer组件实现“隐藏”,这样脚本仍能正常运行:

using UnityEngine;

public class HideObject : MonoBehaviour
{
    private readonly float _disappearDelay = 2f;
    private readonly float _appearDelay = 2f;

    private float _timer;
    private bool _isVisible = true;
    private Renderer _objectRenderer;

    void Start()
    {
        _objectRenderer = GetComponent<Renderer>();
    }

    void Update()
    {
        _timer += Time.deltaTime;

        if (_isVisible)
        {
            if (_timer >= _disappearDelay)
            {
                _objectRenderer.enabled = false;
                _isVisible = false;
                _timer = 0f;
                Debug.Log("hide");
            }
        }
        else
        {
            if (_timer >= _appearDelay)
            {
                _objectRenderer.enabled = true;
                _isVisible = true;
                _timer = 0f;
                Debug.Log("show");
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:54:55