So in my game the character has an grenade launcher, in which the intesity of the explosion of the grenade is defined by how much time the player holds mouse 1 (the longer he holds, the more powerful the explosion will be).
The explosion depends on another script, and the problem with that: I cant find a way to reset the value of the power of the grenade after enough time, so after the first shot, the power stacks up.
public class Shoot : MonoBehaviour {
public GameObject projectile;
public GameObject projectileMid;
public float rocketPower = 1f;
float coolDown = 0.8f;
float pResetTime = 2;
float pResetTimer;
float coolDownTimer;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (coolDownTimer > 0) {
coolDownTimer -= Time.deltaTime;
}
if (coolDownTimer < 0) {
coolDownTimer = 0;
}
//=================================Shooting mechanics below========================================
if (Input.GetMouseButton(0)) {
rocketPower += Time.deltaTime;
//TODO boolean shooting=false
}
if (Input.GetMouseButtonUp(0) && coolDownTimer == 0) {
Vector3 sp = Camera.main.WorldToScreenPoint(transform.position);
Vector3 dir = (Input.mousePosition - sp).normalized;
if (rocketPower <= 1.1) {
//if (!shooting){
GameObject clone;
clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
Rigidbody2D rbody = clone.GetComponent<Rigidbody2D>();
rbody.AddForce(dir * 600);
Destroy(clone, 4);
//TODO boolean shooting=true
}
if (rocketPower > 1.1) {
GameObject cloneMid;
cloneMid = Instantiate(projectileMid, transform.position, transform.rotation) as GameObject;
Rigidbody2D rbody2 = cloneMid.GetComponent<Rigidbody2D>();
rbody2.AddForce(dir * 600);
Destroy(cloneMid, 4);
}
PowerReset();
coolDownTimer = coolDown;
}
}
void PowerReset () {
if (pResetTimer == 2) {
pResetTimer -= Time.deltaTime;
}
if (pResetTimer == 0) {
rocketPower = 0;
pResetTimer = pResetTime;
}
}
}
As you can see I tried to reset the “rocketPower” inside the “PowerReset” function (after 2 seconds the value would reset), but it didnt work, this function did nothing at all.
I can reset it in the end of the Update function however if I do so, it happens too soon before the other scripts that interact with this one have enough time to retrieve the value of rocketPower.