How to Share Variable Values with Multiple Buttons

Asked 1 years ago, Updated 1 years ago, 46 views

There are two buttons, and each has its own variable: price(100), price(50).

Press the button to golds(300) to -=price.
After executing the code below, golds is not shared and seems to have their own values.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class shop:MonoBehavior {

    public DragonStatus status;
    public DeathStatus status2;
    public int Attack;
    public int shield;
    public int price;
    public int golds = 300;
    public int Button;
    public Text goldtext;

    void Start() {
        int gainAttack = Attack;
        intgainshield=shield;

        Button button=this.GetComponent<Button>();

        button.onClick.AddListener(gainItem);
    }

    void gainItem(){
        if(golds>=0){
            golds-=price;
        } else{
            Debug.Log("not enough money";
        }
    }

    public void checker() {
        string str = golds.ToString();
    }

    voidUpdateText(){
        goldtext.text="golds"+golds;
    }
}

c# unity3d

2022-09-30 18:21

1 Answers

The two "buttons" are linked to the two instances of "shop" (right?).
Then, of course, the instance per button is different, so the property "golds" belonging to the instance is different.
If you want to share it, you can think of the following methods:

  • Connecting two buttons to one shop
  • Instance with property "Golds" in a location other than two buttons, Golds in "shop" returns Golds for that instance

"However, when ""price"" and ""golds"" and ""DragonStatus"" and ""Attack"" are mixed in the ""shop"" class, I personally didn't understand what kind of class it was, so it might be off the mark."


2022-09-30 18:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.