- Home /
Trigger a void only once even is used by multiple scripts?
Hey everyone! I've got a gun script that shoots a secondary weapon and every time it fires it reduces the ammo by 1, I''m trying to make cluster shots, with multiple launchers and 1 ammo pool but every time it shoots each script from each launcher accesses the main ammo pool reducing it to 0 when for each Burst of ammo should only reduce it by 1.
how do you Use a void only once even if multiple instances of a script is trying to use it at the same time?
PlayerShooted() basicly is just a Ammocount -= 1;.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SecondaryShoot : MonoBehaviour
{
public SecondaryCount SecondaryCountCS;
public bool CanShoot;
public float nextFire;
public float fireRate = 0.5f;
public GameObject Projectile;
public ShootMobile ShootMobileCS;
// Update is called once per frame
public void Update()
{
if (SecondaryCountCS.SecondaryAmmo > 0 && ShootMobileCS.CanShootSpecial == true)
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(Projectile, transform.position, transform.rotation);
}
SecondaryCountCS.PlayerShooted();
}
}
}
Answer by Llama_w_2Ls · Jun 06, 2021 at 09:17 PM
You can use a flag bool that prevents the function from being run if it is true, and set it back to false every update. For example:
bool HasBeenCalled;
void Update()
{
HasBeenCalled = false;
}
public void MethodThatRunsOnceEveryUpdate()
{
// Exits the function if was called twice or more in one frame
if (HasBeenCalled)
return;
// ... Code ...
HasBeenCalled = true;
}
Answer by zak666 · Jun 07, 2021 at 02:00 AM
got it to work had to add a cool-down timer to reset the bool :) thanks buddy
Your answer
![](https://koobas.hobune.stream/wayback/20220613034651im_/https://answers.unity.com/themes/thub/images/avi.jpg)