Share a variable between scrips, between children

I have a player, who has a ammo variable, from an attached script. This allows for the ammo to increase through collision with ammo packs.

public class Ammo : MonoBehaviour
{
    public float ammo = 10f;
    public float amount = 5f;

void Start()
{

}

private void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.gameObject.CompareTag("AmmoPack"))
    {
        Destroy(hit.gameObject);
        Debug.Log("Hit");
        ammo += (amount/2);
    }
}

}

I have a gun game object with two different scripts to control how the gun works, each have a separate ammo system.

{

public float ammo = 10f;
public float damage = 10f;
public float range = 100f;
public float fireRate = 4f;
public float nextTimeToFire = 0f;
public ParticleSystem muzzleFlash;
public GameObject impact;

public Camera fpsCam;
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    if(Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
    {
        if (ammo > 0)
        {
            nextTimeToFire = Time.time + 1f/fireRate;
            shoot();
            ammo = ammo -= 1;
        }
    }
    
}

^ This is the same on both scripts (One called Gun, the other called Conversion)

What I want is for the ammo to be shared between the two scripts on my gun (Gun and Conversion), while also being shared with my Ammo script on my Player game object.

Hierarchy:

  • ↓Player (Has the ammo script on it)
  • ↓Main Camera
  • ↓Small Gun (Has the Gun and
    Conversion scripts on it)

You can get the ammo script, store it in a variable, and then access any of its public variables/methods.

For example you could do something like this in your gun script:

//Variable to store the ammo script
Ammo ammoScript;

void Start()
 {
//Find the ammo script in the parent object and store it
     ammoScript = GetComponentInParent<Ammo>();
 }
 
 void Update()
 {
//Subtract one from the ammo value of the Ammo script.
       ammoScript.ammo -= 1;
}