Home > Software design >  If condition in C# not working properly with Time.time in Unity
If condition in C# not working properly with Time.time in Unity

Time:05-05

I wrote a code for an object that instantiates by pressing the space bar. Now, I also wanted it to appear only every ten seconds. So, I wrote this code-

public class Player : MonoBehaviour
{

    [SerializeField]
    private GameObject _laserPrefab;

    [SerializeField]
    private float _fireRate=10.0f;

    private float nextFire=0f;


    // Start is called before the first frame update
    void Start()
    {
        transform.position=new Vector3(0,0,0);

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && (Time.time>nextFire)){
            nextFire=Time.time _fireRate;
            Instantiate(_laserPrefab,transform.position new Vector3(0,1f,0),Quaternion.identity);
        }
    }

This code is instantiating the object every time space bar is pressed, but it is not giving a gap of 10 seconds, which I want.

CodePudding user response:

Input.GetKeyDown() only returns true during the frame where the key is detected as down. It will not return true until the user has released the key and pressed it again.

I think you can achieve what you want using Input.GetKey() instead.

CodePudding user response:

You cannot you Time.time in this case as you are not holding the key down for the entire time. You would want to use Time.deltaTime in this case to calculate the elapsed time since the instantiation of the object.

So, in Update() function, keep updating nextFire and when the object is instantiated, reset it to 0.

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && (nextFire > _fireRate)){
        nextFire = 0;
        Instantiate(_laserPrefab,transform.position new Vector3(0,1f,0),Quaternion.identity);
    }

    nextFire  = time.DeltaTime;
}

What happens is when the object is instantiated, nextFire is reset and increments itself every frame. And once the value reaches 10 seconds (which is equal to _fireRate), another object can be instantiated.

  • Related