Search code examples
c#unity-game-enginevariablesintcollider

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


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?


Solution

  • 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;
    }