So I have a Instantiate script for a bow and arrow, and when I tried to delay they speed of the script (fireRate), it does not change the speed of the fire rate in-game. What am I doing wrong with eh variables?
Here is the base fire script:
using UnityEngine;
using System.Collections;
public class UsingInstantiate : MonoBehaviour
{
public Rigidbody rocketPrefab;
public Transform barrelEnd;
public Rigidbody capGun;
private float nextFire = 1.0F;
public float fireRate = 0.5F;
void Update ()
{
if(Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, capGun.rotation) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * 3000);
}
}
}
I think the issue is that you’re using Time.time to control the firing. Based on Unity Time defintion, Time.time is the time that has been elapsed since the game started: Unity - Scripting API: Time.time. Try to add your own counter using Time.DeltaTime
public class UsingInstantiate : MonoBehaviour
{
public Rigidbody rocketPrefab;
public Transform barrelEnd;
public Rigidbody capGun;
private float nextFire = 1.0F;
public float fireRate = 0.5F;
private float fireElapsedTime = 0f; //Will be used to know when to increase the fire rate
void Update ()
{
if(Input.GetButton("Fire1"))
{
//if is time to increase fire rate
if (fireElapsedTime >= nextFire)
{
//reset the counter to 0
fireElapsedTime = 0;
nextFire = Time.time + fireRate;
Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, capGun.rotation) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * 3000);
}
else
{
//just sum the time for the next cycle
fireElapsedTime += Time.deltaTime;
}
}
}
}
Hope this helps