如何在Unity中制作计时器

时间:2019-02-10 21:55:13

标签: c# unity3d

我对自己的代码有疑问。 现在,我使一个文本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秒后消失,下一次,玩家与另一个球碰撞,文本再次出现。 那我该怎么办?

1 个答案:

答案 0 :(得分:1)

您应将coroutineWaitForSeconds一起使用。例如:

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

    yield return new WaitForSeconds(2);

    // Do stuff here to hide the text
}

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

StartCoroutine(OnCollisionCoroutine());