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)

If I understand your request correctly, just declare your variables as “static”.

Example

 public static float ammo = 10f;

at this point you can access the variable (both reading and writing) from any script in your scene.
just call it up like this:

ClassName.ammo

// example - increase range

ClassName.ammo += 3f; // the result will be 13f

To reference a script “ammo”.

Type: Public ammo Ammo;

If you have both the scripts in the scene you can do this.

Public GameObject AmmoGO;

Void start()
{

AmmoGO = Find(‘‘Put the name of the game object with the script here’’);

Ammo = AmmoGO.GetComponent<>();

}

You can reference any variable using Ammo.NameOfTheVariable

Edit: For some reason it doesn’t let me type the script in Get Component. Put Ammo between <>