c# - 如何在 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());
推荐阅读
- java - Dynamodb 本地连接被 Java 拒绝
- azure - 如何在通过 ARM 模板创建部署时从系统变量中读取输入
- makefile - Makefile 动态变量作为先决条件
- c# - 停用组合框中的 SelectionChanged
- python - 将用户重定向到登录时的单独页面
- azure-devops - 如何在服务器(Windows 操作系统)上重新配置 Azure DevOps 代理?
- python - 如何在 python 上使用 pytesseract 阅读其他语言?
- python-3.x - 为什么我在 python3.7.3 上运行时会收到 opencv2 的 ImportError?
- javascript - 如何解决点 .01 返回 0 的两位小数问题
- datetime - 如何通过 SSIS 连接来自 excel 源的日期和时间字段