【问题标题】:Show object for 5 seconds and load new scene显示对象 5 秒并加载新场景
【发布时间】:2015-12-24 16:35:58
【问题描述】:

我正在制作手机游戏,我需要在摧毁物体后显示 5 秒钟的短信。我尝试使用 yield waitforseconds 但不起作用。我也尝试过调用函数。我用行代码 SceneManager.LoadScene ("__Main1"); 创建了一个单独的函数;但我也有同样的问题。

我想显示我的文本 5 秒钟,然后加载新场景。

这是我现在的代码:

void OnTriggerEnter2D (Collider2D other)
    {


        if (other.gameObject.CompareTag ("bomb")) {
            other.gameObject.SetActive (false);
            Destroy (this.gameObject);
            scoretext.SetActive (true); //this text need to be displayed for 5 seconds after destroying game object
            SceneManager.LoadScene ("__Main1");

        }

我希望有人可以帮助解决这个问题。谢谢。

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    您不能销毁对象并在其上启动协程。您需要引用此文本并在执行协程时保持活动状态的其他对象。

    编辑:

    更准确地说:

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.CompareTag ("bomb")) {
            other.gameObject.SetActive (false);
    
            scoretext.SetActive (true); //this text need to be displayed for 5 seconds after destroying game object
            waitEndDisable.WaitAndDisable(scoretext); // here we go ;)
            Destroy (this.gameObject);
        }
    

    在其他脚本上,即在 active GameObject 上运行:

    public void WaitAndDisable(GameObject obj)
    {
        StartCoroutine(WaitAndDisableCoroutine(obj));    
    }
    
    IEnumerator WaitAndDisableCoroutine(GameObject obj)
    {
        yield return new WaitForSeconds(5f);
        SceneManager.LoadScene ("__Main1");
        obj.SetActive(false);
    }
    

    正如您在主脚本中看到的,您需要使用 WaitAndDisable 方法引用脚本。确保此对象处于活动状态(gameObject.activeSelf == true)。

    【讨论】:

    • 好的,但在我的情况下如何。我一整天都在尝试。
    • 已编辑,对外面的代码感到抱歉,但对此无能为力。
    • 这条线是红色的 waitEndDisable.WaitAndDisable(scoretext); // 我们开始 ;) 在我的代码上。我在文本元素上附加了新脚本。 (因为我需要显示文本并保持 5 秒)
    • waitEndDisable 是对 您的脚本 的引用,其中包含我向您展示的方法;)
    • 对不起,它不起作用。我不知道。我认为这是我的文本对象的问题。我试图在关卡结束时显示分数并将它们保持 5 秒,但什么也没有......
    【解决方案2】:

    您可以使用 Enumerator 等待几秒钟。

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.gameObject.CompareTag ("bomb")) 
        {
            other.gameObject.SetActive(false);
            StartCoroutine(Foo());
        }
    }
    
    IEnumerator Foo()
    {
        scoretext.SetActive (true); //this text need to be displayed for 5 seconds after destroying game object
        yield return new WaitForSeconds(5f);
        SceneManager.LoadScene ("__Main1");
    }
    

    您应该添加 using System.Collections 以使用枚举器。

    【讨论】:

    • 如果你说什么不起作用,我认为人们可以提供更多帮助
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2016-03-18
    • 2015-03-09
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多