'Ammo Limitations in Unity2D (Top Down)

I am fairly new to C# and am currently trying to expand upon Ruby's Tutorial by adding in an ammo limitation function that controls the amount of Cogs Ruby has at a time as well as her ability to pick up extra ammo. Right now my script is not limiting the number of rounds Ruby can fire and is stuck displaying "Cogs: 4". She is able to pick up the ammo (pickup set to is trigger) but it is not updating the Cogs. Please help, I would love to understand what I am possibly doing wrong as my code is not displaying any errors.

Ruby's Controller Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;



public class RubyController : MonoBehaviour
{
    public float speed = 3.0f;
   
    public int maxHealth = 5;
    
    public GameObject projectilePrefab;


    public int Score;
   
    int Cog;
    public static int CogAmount = 4;


    public TextMeshProUGUI scoreText;
    public TextMeshProUGUI CogText;


    public GameObject winTextObject;
    public GameObject loseTextObject;


    public GameObject BackgroundMusicObject;
    public GameObject WinSoundObject;
    public GameObject LoseSoundObject;
   
    
    public AudioClip throwSound;
    public AudioClip hitSound;
    public AudioClip collectedClip;
  
    
    public int health { get { return currentHealth; }}
    int currentHealth;

    public float timeInvincible = 2.0f;
    bool isInvincible;
    float invincibleTimer;
    
    Rigidbody2D rigidbody2d;
    float horizontal;
    float vertical;
    
    public ParticleSystem HealthIncrease;
    public ParticleSystem HealthDecrease;

    Animator animator;
    Vector2 lookDirection = new Vector2(1,0);
    
    AudioSource audioSource;
    
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        
        currentHealth = maxHealth;

        audioSource = GetComponent<AudioSource>();

        Score = 0;
        Cog = 4;

        SetCogText();

        winTextObject.SetActive(false);
        loseTextObject.SetActive(false);

        WinSoundObject.SetActive(false);
        LoseSoundObject.SetActive(false);

        HealthIncrease.Stop();
        HealthDecrease.Stop();

    }

    public void ChangeScore(int scoreAmount)
    {
        {   
            Score++;
            scoreText.text = "Fixed Robots: " + Score.ToString();
        }
        
    }


    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        
        Vector2 move = new Vector2(horizontal, vertical);
        
        if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
        {
            lookDirection.Set(move.x, move.y);
            lookDirection.Normalize();
        }
        
        animator.SetFloat("Look X", lookDirection.x);
        animator.SetFloat("Look Y", lookDirection.y);
        animator.SetFloat("Speed", move.magnitude);
        
        if (isInvincible)
        {
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer < 0)
                isInvincible = false;
        }
        
        if(Input.GetKeyDown(KeyCode.C) && Cog >= 1)
        {
           Cog = Cog -1;
            Launch();
        }
        
        else if (Input.GetKeyDown(KeyCode.C) && Cog ==0)
        {
            return;
        }
        
        if (Input.GetKeyDown(KeyCode.X))
        {
            RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC"));
            if (hit.collider != null)
            { 
                NonPlayerCharacter character = hit.collider.GetComponent<NonPlayerCharacter>();
                if (character != null)
                {
                    character.DisplayDialog();
                }
            }
        }

        if (CogAmount > 0)
        {
            CogText.text = "Cogs: " + CogAmount;
        }

        else if (CogAmount <= 0)
        {
            CogText.text = "Out of Cogs!";
        }

        if (Score >= 4)
        {
            winTextObject.SetActive(true);
            {
                if(Input.GetKeyDown(KeyCode.R))
                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
                speed = 0;
                WinSoundObject.SetActive(true);
                BackgroundMusicObject.SetActive(false);
            }
        }

        else if (currentHealth == 0)
        {
            loseTextObject.SetActive(true);
            {
                if(Input.GetKeyDown(KeyCode.R))
                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
                speed = 0;
                LoseSoundObject.SetActive(true);
                BackgroundMusicObject.SetActive(false);
            }
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }
    
    void FixedUpdate()
    {
        Vector2 position = rigidbody2d.position;
        position.x = position.x + speed * horizontal * Time.deltaTime;
        position.y = position.y + speed * vertical * Time.deltaTime;

        rigidbody2d.MovePosition(position);
    }

    void SetCogText()
    {
        CogText.text = "Cogs: " + Cog.ToString();
    }


    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Cog"))
        {
            Cog = Cog + 3;
            other.gameObject.SetActive(false);
        
        }
    }


    public void ChangeHealth(int amount)
    {
        if (amount < 0)
        {
            if (isInvincible)
                return;
            
            isInvincible = true;
            invincibleTimer = timeInvincible;
            GameObject projectileObject = Instantiate(HealthDecrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);

            Projectile projectile = projectileObject.GetComponent<Projectile>();
            PlaySound(hitSound);
        }

        if (amount < 5)
        {
            GameObject projectileObject = Instantiate(HealthIncrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
        }
        

        currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
        
        UIHealthBar.instance.SetValue(currentHealth / (float)maxHealth);
    }
    
    void Launch()
    {
        GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);

        Projectile projectile = projectileObject.GetComponent<Projectile>();
        projectile.Launch(lookDirection, 300);

        animator.SetTrigger("Launch");
        
        PlaySound(throwSound);

    } 

    public void PlaySound(AudioClip clip)
    {
        audioSource.PlayOneShot(clip);
    }
}

Projectile Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
    
public class Projectile : MonoBehaviour
{
    Rigidbody2D rigidbody2d;
    
    void Awake()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
    }
    
    public void Launch(Vector2 direction, float force)
    {
        rigidbody2d.AddForce(direction * force);
    }
    
    void Update()
    {
        if(transform.position.magnitude > 1000.0f)
        {
            Destroy(gameObject);
        }
    }
    
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Enemy") 
        {   
            EnemyController e = other.collider.GetComponent<EnemyController>();
              if (e != null)

            {
                e.Fix();
            }
        }

        else if (other.gameObject.tag == "HardEnemy") 
        {    
            HardEnemyController e = other.collider.GetComponent<HardEnemyController>(); 
              if (e != null)

            {
                e.Fix();
            }
        }
        Destroy(gameObject);
    }
}


Solution 1:[1]

Ok after a bit of trial and error I believe I have finally fixed the issue. I will post my updated script for anyone wanting to compare and/or learn from my mistakes lol. Basically I utilized a SetCogText(); variable in the start function and throughout my code to update my TextMeshPro; and removed the public static int CogAmount = 0; I initially used in my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;



public class RubyController : MonoBehaviour
{
    public float speed = 3.0f;
   
    public int maxHealth = 5;
    
    public GameObject projectilePrefab;


    public int Score;
   
    int Cog;
    


    public TextMeshProUGUI scoreText;
    public TextMeshProUGUI CogText;


    public GameObject winTextObject;
    public GameObject loseTextObject;
    public GameObject LevelOneTextObject;


    public GameObject BackgroundMusicObject;
    public GameObject WinSoundObject;
    public GameObject LoseSoundObject;

    

    private static int Level;
   
    
    public AudioClip throwSound;
    public AudioClip hitSound;
    public AudioClip collectedClip;
  
    
    public int health { get { return currentHealth; }}
    int currentHealth;

    public float timeInvincible = 2.0f;
    bool isInvincible;
    float invincibleTimer;
    
    Rigidbody2D rigidbody2d;
    float horizontal;
    float vertical;
    
    public ParticleSystem HealthIncrease;
    public ParticleSystem HealthDecrease;

    Animator animator;
    Vector2 lookDirection = new Vector2(1,0);
    
    AudioSource audioSource;
    
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        
        currentHealth = maxHealth;

        audioSource = GetComponent<AudioSource>();

        Score = 0;
        Cog = 4;

        SetCogText();

        winTextObject.SetActive(false);
        loseTextObject.SetActive(false);
        LevelOneTextObject.SetActive(false);

        WinSoundObject.SetActive(false);
        LoseSoundObject.SetActive(false);

        HealthIncrease.Stop();
        HealthDecrease.Stop();

    }

    public void ChangeScore(int scoreAmount)
    {
        {   
            Score++;
            scoreText.text = "Fixed Robots: " + Score.ToString();
        }

        if (Level == 1)
        {
            if (Score == 4)
            {
                LevelOneTextObject.SetActive(true);
            }  
        }

        if (Level == 2)
        { 
          
          if(Score == 4)
            {
                winTextObject.SetActive(true);
                {
                    if(Input.GetKeyDown(KeyCode.R))
                    SceneManager.LoadScene(1);
                    speed = 0;
                    WinSoundObject.SetActive(true);
                    BackgroundMusicObject.SetActive(false);
                }
            }   
        }     
    }




    // Update is called once per frame
    void Update()
    {
        horizontal = Input.GetAxis("Horizontal");
        vertical = Input.GetAxis("Vertical");
        
        Vector2 move = new Vector2(horizontal, vertical);
        
        if(!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f))
        {
            lookDirection.Set(move.x, move.y);
            lookDirection.Normalize();
        }
        
        animator.SetFloat("Look X", lookDirection.x);
        animator.SetFloat("Look Y", lookDirection.y);
        animator.SetFloat("Speed", move.magnitude);
        
        if (isInvincible)
        {
            invincibleTimer -= Time.deltaTime;
            if (invincibleTimer < 0)
                isInvincible = false;
        }
        
        if(Input.GetKeyDown(KeyCode.C) && Cog >= 1)
        {
           Cog = Cog -1;
           SetCogText();
            Launch();

        }
        
        else if (Input.GetKeyDown(KeyCode.C) && Cog ==0)
        {
            return;
        }
        
        if (Input.GetKeyDown(KeyCode.X))
        {
            RaycastHit2D hit = Physics2D.Raycast(rigidbody2d.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC"));
            if (hit.collider != null)
            {
                if (Score >= 4)
                {
                    Level = 2;
                    SceneManager.LoadScene(2);
                    Score = 4;
                }

                else if (Score < 4)
                {
                    NonPlayerCharacter character = hit.collider.GetComponent<NonPlayerCharacter>();
                    if (character != null)

                    {
                        character.DisplayDialog();
                    }
                }
            }
        }


        if (currentHealth == 0) 
        {
            loseTextObject.SetActive(true);
            {
                if(Input.GetKeyDown(KeyCode.R))
                SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
                speed = 0;
                LoseSoundObject.SetActive(true);
                BackgroundMusicObject.SetActive(false);
            }
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }
    
    void SetCogText()
    {
     if (Cog > 0)
        {
            CogText.text = "Cogs: " + Cog.ToString();
        }

        else if (Cog <= 0)
        {
            CogText.text = "Out of Cogs!";
            SetCogText();
        }
    }


    void FixedUpdate()
    {
        Vector2 position = rigidbody2d.position;
        position.x = position.x + speed * horizontal * Time.deltaTime;
        position.y = position.y + speed * vertical * Time.deltaTime;

        rigidbody2d.MovePosition(position);
    }



    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Cog"))
        {
            Cog = Cog + 3;
            other.gameObject.SetActive(false);
            SetCogText();
        
        }
    }


  public void ChangeHealth(int amount)
    {
        if (amount < 0)
        {
            if (isInvincible)
                return;
            
            isInvincible = true;
            invincibleTimer = timeInvincible;
            GameObject projectileObject = Instantiate(HealthDecrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);

            Projectile projectile = projectileObject.GetComponent<Projectile>();
            PlaySound(hitSound);
        }

        if (amount < 5)
        {
            GameObject projectileObject = Instantiate(HealthIncrease.gameObject, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);
        }
        

        currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
        
        UIHealthBar.instance.SetValue(currentHealth / (float)maxHealth);
    }
    
    void Launch()
    {
        GameObject projectileObject = Instantiate(projectilePrefab, rigidbody2d.position + Vector2.up * 0.5f, Quaternion.identity);

        Projectile projectile = projectileObject.GetComponent<Projectile>();
        projectile.Launch(lookDirection, 300);

        animator.SetTrigger("Launch");
        
        PlaySound(throwSound);

    } 

   public void PlaySound(AudioClip clip)
    {
        audioSource.PlayOneShot(clip);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Holger Just