jrdoda
1
Hi
I have a script that fires a prjectile in my game but i want it to fire two, each after a short delay.
I’m not sure what code i need to add to make it fire twice.
It is part of a powerup script:
if (hasMachineGun) {
GameObject cloneMachineGun;
Vector3 fireMachineGun = transform.forward * projectileSpeed;
if(Input.GetButtonDown("Fire1")){
cloneMachineGun = (GameObject)Instantiate(machineGun, machineGunSocket.transform.position, transform.rotation);
cloneMachineGun.rigidbody.AddForce(fireMachineGun);
playerState = PlayerState.CarNormal;
changeState = true;
}
}
I think that is all thats needed?
Thanks
I’m not 100% sure how your code works but you can fire twice or x-amount of times using for-loop.
if (hasMachineGun) {
GameObject cloneMachineGun;
Vector3 fireMachineGun = transform.forward * projectileSpeed;
if(Input.GetButtonDown("Fire1")){
for (int i = 0; i < 2; i++){ // Fire twice.
cloneMachineGun = (GameObject)Instantiate(machineGun, machineGunSocket.transform.position, transform.rotation);
cloneMachineGun.rigidbody.AddForce(fireMachineGun);
}
playerState = PlayerState.CarNormal;
changeState = true;
}
}
Adding delay is a little more complicated thing. You could use invoke or coroutine. In both cases you have to make function for firing.
I made a coroutine example for you, but you should definitely check how they work:
http://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines
if (hasMachineGun) {
if(Input.GetButtonDown("Fire1")){
StartCoroutine(FireMachineGun());
playerState = PlayerState.CarNormal;
changeState = true;
}
}
float fireDelay = 0.2f; // Delay before both shots
IEnumerator FireMachineGun()
{
GameObject cloneMachineGun;
Vector3 fireMachineGun = transform.forward * projectileSpeed;
for (int i = 0; i < 2; i++){
yield return new WaitForSeconds(fireDelay);
cloneMachineGun = (GameObject)Instantiate(machineGun, machineGunSocket.transform.position, transform.rotation);
cloneMachineGun.rigidbody.AddForce(fireMachineGun);
}
}