Control of a public static int from different scripts.

I have a game counter I plan to use to sequence a number of events (animations and text) based on two buttons; one to increment the counter and one to reset the counter back to 0. I have setup 3 scripts and am trying to use the onClick function of the new GUI system to modify the counter. All scripts are attached to the same game object.

Just now i am not getting anything to print in the console and neither of the buttons do anything :frowning:

The first creates the public static int “nextNum”

using UnityEngine;
using System.Collections;

public class SetButInc : MonoBehaviour {

public static int nextNum;

void Start () {

		nextNum=0;
		Debug.Log (nextNum);
	
	}
	
}

The second is attached to the onclick function of the increment button.

using UnityEngine;
using System.Collections;

public class PanelButInc : MonoBehaviour {

public void PanelButtonInc() {

	SetButInc.nextNum ++;

	}
}

And the third is attached to the onclick function of the reset button.

using UnityEngine;
using System.Collections;

public class LogoButReset : MonoBehaviour {

public void LogoButtonReset() {

SetButInc.nextNum=0;
				
}

}

Many thanks.

Is SetButInc actually attached to a GameObject in the scene? If that script doesn't debug in Start(), then your other scripts won't do anything.

All three scripts are attached to a UI Manager GameObject. Not sure how to amend the script based on your 2nd comment?

2 Answers

2

[SerializeField] private Button Button1 = null; // assign in the editor
[SerializeField] private Button Button2 = null; // assign in the editor

void Start() {
 Button1.onClick.AddListener(() => { LogoButtonReset();});
 Button2.onClick.AddListener(() => { PanelButtonInc();});
}

public void PanelButtonInc() {
 
    SetButInc.nextNum ++;
 
    }

public void LogoButtonReset() {

SetButInc.nextNum=0;
 
}

Can you advise how to use this script? I assume its doing the job of my 3 scripts in 1, however when I add it to my UI Manager GameObject I get the following error; Assets/ButControl.cs(6,34): error CS0246: The type or namespace name `Button' could not be found. Are you missing a using directive or an assembly reference?

Attach SetButInc to a GameObject in the scene.

You don't actually need to do this to access static members...

all 3 scripts are attached to the same GameObject.