How can I make variables stay the same when a new Prefab spawns.

Hi I’m pretty new to coding but I’m trying to make a system where when you kill an enemy, it has a chance to spawn a grenade you can pick up, and each one you pick up, it will add 1 to the grenade count text. Here is my code so far:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PickUp : MonoBehaviour {
    GameObject player;
    public int GrenadeCount;
    Text Grenades;
    void Start () {
        player = GameObject.FindGameObjectWithTag ("Player");
        Grenades = GameObject.Find ("GrenadeText").GetComponent<Text> ();
    }


    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == player)
        {
            GrenadeCount = GrenadeCount + 1;
            Grenades.text = "Grenades:" + GrenadeCount;
            Destroy (gameObject);

        }
    }


}

The problem I’m having is each time a new grenade spawns, it resets GrenadeCount to 0 so instead of adding 1 each time, it goes from 0 at the beginning of the game, then up to 1 after you pick up the first one but after a new one spawns it goes back to 0 so when you pick it up it just goes back to 1. The result is the text only reading “Grenades:0” at the start then after you pick one up it goes to “Grenades:1” but it never goes above one. is there anyway I can make the GrenadeCount variable communicate with the same variable on other instances of the object?

You could make GrenadeCount static

public static int GrenadeCount.

But in all honesty, you should really have this on a manager type script. That way you access the ammoManager or whatever you want it to be. You’ll call a method to add a grenade and update the text or when a player using the grenade, you’ll call a method on the ammoManager to subtract a grenade.

So yes, method two is a better way to go. Your grenade should not be responsible for updating text and tracking numbers since it doesn’t stay in the scene. (you’re destroying it)

You can use static to make all instances of a class share the same member.

Use with caution.

Thank you, I made a seperate Grenade ammo manager and it works now.