英文:
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
这将禁用渲染器组件。
渲染器应该被重命名为MeshRenderer或SpriteRenderer等。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论