首页 > 解决方案 > 如何在 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 秒后消失,下一次,玩家与另一个球碰撞时,文字再次出现。那么我能做什么呢?

标签: c#unity3d

解决方案


您应该使用带有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());

推荐阅读