Home > Net >  How to increase and update the int two functions
How to increase and update the int two functions

Time:08-04

I tried to increase an int value on button click, but it's value doesn't update in another function.

Public class example: MonoBehavior{
int x = 0;

  void Update(){
     Debug.Log(x); //x = 0
  }

  //Functions called in unity button click
  void UIBtnClicked(){
     x  ;
     Debug.Log(x); //x = 1
  }

}

CodePudding user response:

If the class isn't inherited from MonoBehaviour, it is just a regular function. Won't behave like and Update in a MonoBehaviour.

CodePudding user response:

You can create an empty object on scene with tag ( tag : "emptyObject" etc.) , Then you can add a script on this empty object with int prop.

Public class XController: MonoBehavior{
  public int x = 0;
}

Then you can find this empty object from tag and increase or decrease x value like this.

Public class example: MonoBehavior{
    private XController xController;

    void Start(){
      emptyGameObject = GameObject.FindGameObjectsWithTag("emptyObject").GetComponent<XController>();
    }
    
    void Update(){
      Debug.Log(xController.x); //x = 0
    }

    //Functions called in unity button click
    void UIBtnClicked(){
      xController.x  ;
      Debug.Log(xController.x); //x = 1
    }
}

You can always reach the same instance of xController and change the value.

  • Related