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

huangapple go评论68阅读模式
英文:

How do I fix the hide/show script of object?

问题

I have a script to hide the object after 2 seconds and then show it after 2 seconds too, but it just hides and does not show again. I use Debug.Log to check, but the console only appears: "hide." I tested it with an empty object.

英文:

I have a script to hide the object after 2 seconds and then show it after 2 seconds too but it just hide and not show again:

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");
            }
        }
    }
}

I use Debug.Log to check but the console only appear: hide

I test with the empty object

答案1

得分: 4

你正在禁用你的gameObject以使其消失(使用 gameObject.SetActive(false); ),这也会停止附加到它的所有脚本。在禁用状态下,你的代码将无法再运行Update()函数,并且它永远不会再次出现。你需要从另一个对象中运行这段代码,或者不要禁用整个gameObject。

英文:

You are disabling your gameObject to make it disappear (using gameObject.SetActive(false);) , this also stops all the scripts attached to it. Your code will not bo able to run the Update() function anymore while disabled and it will never appear. You need to run this code from another object or not disable the whole gameObject

答案2

得分: 0

Show无法在这种情况下工作,因为Update方法无法在gameobject.Setactive = false上工作。

相反,你可以使用

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

这将禁用渲染器组件。

渲染器应该被重命名为MeshRendererSpriteRenderer等。

英文:

Show wont work on this situation because Update method wont work on gameobject.Setactive = false

Instead you can use

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

This will disable renderer component.

Renderer should be renamed with either MeshRenderer or SpriteRenderer etc.

huangapple
  • 本文由 发表于 2023年4月19日 19:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定