Hi again!
I'm trying to prevent my player from shooting as fast as he can press the Space Key.
I'm programming in C# right now and I find Coroutines a little bit too complex to handle.
Instead, what I came up with is this:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public GameObject myProjectile;
public float nextFire = -1.0f;
void Start () {
nextFire = Time.time;
}
void Update () {
//SHOOTING
if(Time.time >= nextFire){
if(Input.GetKeyDown(KeyCode.Space)){
nextFire = nextFire+1;
myProjectile.transform.position = new Vector3 ( Player.position.x, Player.position.y, Player.position.z);
Instantiate(myProjectile);
}
}
}
}
This script works good in my 2d game project, except for one issue: Sometimes, when I press Space really really fast, I can shoot two or three times in a row no matter what the code says... especially when I intentionally pick up the peace to fool this limitation.
I tried to change the GetKeyDown with GetKey or GetKeyUp and nothing changes for the good.
It seems my solution is either wrong or incorrectly applied.
Is this oversight somehow implied by my code and nothing can be done to solve this issue, apart from adopting a new solution?
In this case, what would you suggest?
Thanks for your time!
↧