如何修复对象的隐藏/显示脚本?

问题描述 投票:0回答:2

我有一个脚本可以在 2 秒后隐藏对象,然后在 2 秒后显示它,但它只是隐藏而不再显示:

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

public class HideObject : MonoBehaviour
{
    private float disappearTime = 2f;
    private float appearTime = 2f;

    private float disappearTimer = 0f;
    private float appearTimer = 0f;

    private bool isBlockVisible = true;

    void Update()
    {
        if (isBlockVisible)
        {
            disappearTimer += Time.deltaTime;
            if (disappearTimer >= disappearTime)
            {
                gameObject.SetActive(false);
                isBlockVisible = false;
                disappearTimer = 0f;
                Debug.Log("hide");
            }
        }
        else
        {
            appearTimer += Time.deltaTime;
            if (appearTimer >= appearTime)
            {
                gameObject.SetActive(true);
                isBlockVisible = true;
                appearTimer = 0f;
                Debug.Log("show");
            }
        }
    }
}

我用Debug.Log查看但是控制台只出现:hide

我用空对象测试

c# unity3d unityscript
2个回答
1
投票

您正在禁用您的游戏对象以使其消失(使用

gameObject.SetActive(false);
),这也会停止所有附加到它的脚本。您的代码在禁用时将无法再运行 Update() 函数,并且它永远不会出现。您需要从另一个对象运行此代码或不禁用整个游戏对象


0
投票

Show 不适用于这种情况,因为 Update 方法不适用于 gameobject.Setactive = false

相反,您可以使用

myGameObject.GetComponent<Renderer>().enabled = false

这将禁用渲染器组件。

渲染器应重命名为 MeshRendererSpriteRenderer

© www.soinside.com 2019 - 2024. All rights reserved.