我有一个简单的便签,可以让玩家单击“ Disparo”按钮(在本例中为左键)时射击预制件。现在它坏了,因为您可以向点击发送垃圾邮件并每秒射击一次。我不知道如何为此添加冷却时间,以使您只能在每个特定的时间拍摄。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class ProjectileShooter : MonoBehaviour
{
public AudioClip disparo;
GameObject prefab;
public float shootSpeed;
// Start is called before the first frame update
void Start()
{
prefab = Resources.Load("Projectile") as GameObject;
}
// Update is called once per frame
void Update()
{
if (CrossPlatformInputManager.GetButtonDown("Disparo"))
{
GameObject Projectile = Instantiate(prefab) as GameObject;
Projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
Rigidbody rb = Projectile.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * shootSpeed;
Destroy(Projectile, 2.2f);
}
}
}
答案 0 :(得分:0)
一种实现所需目标的方法是设置一个布尔值,以检查进程是否处于冷却状态。
private bool isInCooldown = false;
然后,在您的if语句中,您可以在完成计算后调用新方法。如Unity docs调用方法中所述:
以秒为单位调用方法methodName。
if (CrossPlatformInputManager.GetButtonDown("Disparo"))
{
if(!isInCooldown){
//Your code here
Invoke("ResetCooldown", 2f);
isInCooldown = true;
}
}
ResetCooldown方法很简单:
private void ResetCooldown () {
isInCooldown = false;
}
希望这会有所帮助。
答案 1 :(得分:0)
以下脚本可轻松设置冷却时间。您可以通过更改 shootcoolTime 来设置冷却时间。并且不要触摸 youCanShootNow 。该变量仅在您可以再次拍摄时用于节省时间;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class ProjectileShooter : MonoBehaviour
{
public AudioClip disparo;
GameObject prefab;
public float shootSpeed;
public float shootcoolTime;
float youCanShootNow;
// Start is called before the first frame update
void Start()
{
prefab = Resources.Load("Projectile") as GameObject;
youCanShootNow = 0;
}
public void Update()
{
if (youCanShootNow < Time.time)
{
if (CrossPlatformInputManager.GetButtonDown("Disparo"))
{
GameObject Projectile = Instantiate(prefab) as GameObject;
Projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
Rigidbody rb = Projectile.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * shootSpeed;
Destroy(Projectile, 2.2f);
youCanShootNow = Time.time + coolTime;
}
}
}
}