gpt4 book ai didi

c# - 如何降低Unity2D中的实例化频率

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:26 25 4
gpt4 key购买 nike

我正在尝试像这样降低拍摄频率:

public class createShot : MonoBehaviour {

public GameObject shot;

void Update()
{
StartCoroutine("Shot");
}

IEnumerator Shot()
{
if (Input.GetKey("space"))
{
Instantiate(shot, transform.position, transform.rotation);
yield return new WaitForSeconds(1f);
}
}
}

但它在不到一秒的时间内不断发送大量照片...有人可以帮忙吗?这是Unity5中的2D项目

最佳答案

也许你想要更像这样的东西:

float elapsedTime;
[SerializeField]
float targetTime = 1f;

void Update()
{
elapsedTime += Time.deltaTime;

if(elapsedTime >= targetTime && Input.GetKey(KeyCode.Space))
{
elapsedTime = 0;
Instantiate(shot, transform.position, transform.rotation);
}
}

这会增加一个计时器 elapsedTime 并检查它是否超过 targetTime

我也鼓励您尽可能停止使用字符串。不要在调用方法时或请求 GetKey 中的 key 之类的东西时使用它们。它们会产生垃圾并降低您的软件速度。

关于c# - 如何降低Unity2D中的实例化频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com