I want to use one int in two scripts and decrease it in the second one

110 Views Asked by At

I want to use this int in the two scripts: public int wood; I want the value of the int to be the same in both scripts.

This is my first script:

public class Tree : 
  
MonoBehaviour { public int wood;
    
     private void OnTriggerEnter2D(Collider2D collision)
     {
         wood += 1;
     }
    }

This is my second script which I want the wood to use in it:

public class Base : MonoBehaviour {

 private void OnTriggerEnter2D(Collider2D collision)
 {
 }
}

I want to decrease the wood value in OnTriggerEnter2D. How do I do that?

2

There are 2 best solutions below

5
ChilliPenguin On BEST ANSWER

You can add the button component to your gameobject.(To get this component in code use Button btn = Gameobject.GetComponent<Button>();. To detect a click on the button you can use the onclick event the button has.

void Start(){
    btn.onClick.AddListener(ButtonClicked);
}
void ButtonClicked(){
    //code
}

You can also add the OnMouseDown and OnMouseUp functions to create a button(this would only require the collider component, and not the button component.

void OnMouseDown(){
    clicking = true;
}
void OnMouseUp(){
    clicking = false;
}
0
Lotan On

When a button is clicked it throws an event. So you need to register what you want to do when this event fires.

There are multiple ways, but one could be like:

buttonVariable.onClick.AddListener(OnButtonDoSomething);

Using lambda expresion will be:

button.onClick.AddListener(() => OnButtonDoSomething());

So you need to declare this on Start, OnEnable or Awake method in any of your scripts. And then have a Button reference so you can store your buttonVariableand finally declare your method OnButtonDoSomething.

To fit your question, you'll store a boolean variable called buttonGotClicked and in your new created method, set this boolean like:

private void OnButtonDoSomething()
{
    buttonGotClicked = true;
}

Then you can do if(buttonGotClicked)...