Static Integers Problem

Hi!
I have here these two scripts:

Script A - This goes on the Tree object.

public class CutTree : MonoBehaviour 
{
	public AudioClip ChopSound;
	public GameObject Tree;

	public static int amountHitTree;
	
	void Start()
	{
		Tree = this.gameObject;
		amountHitTree = 0;
	}
	
	void OnMouseOver()
	{
		if(Input.GetMouseButtonDown(0))
		{
			_Manager.Wood += 1;
			audio.PlayOneShot(ChopSound);
			amountHitTree += 1;
		}
	}

	void Update()
	{
		if (amountHitTree == 5)
		{
			Destroy(gameObject);
		}
	}
}

and Script B - This goes on an empty gameObject.

public class _Manager : MonoBehaviour 
{

	public static int Wood;
	public static int Stone;
	public static int Meat;

	public AudioClip treeFallSound;
	private bool hasPlayed = false;

	void OnGUI()
	{
		GUILayout.Label("Wood: " + _Manager.Wood);
		GUILayout.Label("Stone: " + _Manager.Stone);
	}

	void Update()
	{
		if(CutTree.amountHitTree == 5)
		{
			if(!hasPlayed)
			{
				audio.PlayOneShot(treeFallSound);
				hasPlayed = true;
			}
		}
	}
}

I have the ‘amountHitTree’ int set to static because of sound issues, and a OneShot playing an infinite amount of times every frame.
The problem is that when I hit one tree 5 times, it destroys all the others. I know why; this is because the ‘amountHitTree’ int is static–is there any other way i can fix this?

As gjf already said, static means – shared between all instances of this class. No matter how many CutTrees you make, amountHitTree will always be pointing to the same variable/value. It will be there even if you have 0 trees.

You should generally not use “static” unless you know what you are doing. You could theoretically solve your issue with statics in CutTree, but you shouldn’t.

Add public static _Manager Instance; field to _Manager class and add Instance = this; to its Awake() method. This will be a singleton (search around for singleton pattern), a simple proper example of using statics.

Then add public void TreeCut(CutTree tree) { } method to your _Manager. This will be called by any tree that gets cut down.

Then in CutTree make amountHitTree non-static and in Update() when it has been hit 5 times, call _Manager.Instance.TreeCut(this);. Now, every time a tree gets hit 5 times, it will tell this to the manager. The manager can then play sounds or count resources, etc.

In fact, you should probably apply the same principle to counting resources.

P.S. Although not an issue with singleton solution, you have two updates: _Manager.Update() and CutTree.Update(). They can run in any order. This means CutTree may destroy itself before _Manager ever checks it in your version.