繁体   English   中英

如何在Unity中制作计时器

[英]How to make a timer in Unity

我对自己的代码有疑问。 现在,我使一个文本UI在碰撞后显示在屏幕上,并且我还想让文本在2秒钟后消失,以便在再次发生新的碰撞后可以再次显示它。 那么,我该如何设置计时器来获取此功能? 非常感谢!

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

public class CollisionWithPlayer : MonoBehaviour
{
    int score;

    // Start is called before the first frame update
    void Start()
    {
        score = 0;
        GameObject.Find("message").GetComponent<Text>().text ="";
        GameObject.Find("collect").GetComponent<Text>().text = "";
        GameObject.Find("score").GetComponent<Text>().text = "";

    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnCollisionEnter(Collision collision)
    {
        print("Collided with " + collision.collider.gameObject.tag);
        if (collision.collider.gameObject.tag == "pick_me")
        {
            GameObject.Find("collect").GetComponent<Text>().text = "You have collected an object!";
            Destroy(collision.collider.gameObject);
            //yield return new WaitForSeconds(2);
            //Destroy(GameObject.Find("collect"));
            score++;
            GameObject.Find("score").GetComponent<Text>().text = "score = " + score;
            print("Score " + score);

        }
        if (collision.collider.gameObject.name == "end" && score == 4)
        {
            print("Congratulations!");
            GameObject.Find("message").GetComponent<Text>().text = "Congratulations!";
        }
    }
}

在我的代码中,我有4个球属于“ pick_me”。我想要文本“您已经收集了一个物体!” 出现在玩家与球碰撞时,然后在2秒后消失,下一次,玩家与另一个球碰撞,文本再次出现。 那我该怎么办?

您应该将协程WaitForSeconds一起使用 例如:

IEnumerable OnCollisionCoroutine()
{
    // Do stuff here to make the text visible

    yield return new WaitForSeconds(2);

    // Do stuff here to hide the text
}

然后,当检测到冲突时,请调用:

StartCoroutine(OnCollisionCoroutine());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM