Базовая система закупок в Unity3d

В моей игре есть возможность получить МОНЕТУ, при определенной сумме можно выпускать новые скины.

В настоящее время счет монет хранится правильно.

У меня есть холст пользовательского интерфейса, где есть варианты скинов, я хочу знать, как купить эти скины, если у игрока достаточно монет, или что ничего не происходит, если у него недостаточно.

Следуйте приведенным ниже кодам.

CoinScore

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

public class BeeCoinScore: MonoBehaviour
{

    public static BeeCoinScore instance;

    public static int coin = 0;  
    public int currentCoin = 0;
    string highScoreKey = "totalCoin";

    Text CoinScore;                      // Reference to the Text component.


    void Awake ()
    {
        // Set up the reference.
        CoinScore = GetComponent <Text> ();

    }
    void Start(){

        //Get the highScore from player prefs if it is there, 0 otherwise.
        coin = PlayerPrefs.GetInt(highScoreKey, 0);    
    }
    public void AddBeeCoinScore (int _point) {

        coin += _point;
        GetComponent<Text> ().text = "Bee Coins: " + coin;

    }


    void Update ()
    {
        // Set the displayed text to be the word "Score" followed by the score value.
        CoinScore.text = "Bee Coins: " + coin;
    }


    void OnDisable(){

        //If our scoree is greter than highscore, set new higscore and save.
        if(coin>currentCoin){
            PlayerPrefs.SetInt(highScoreKey, coin);
            PlayerPrefs.Save();
        }
    }

}

Скрипт для добавления баллов в CoinScore

using UnityEngine;
using System.Collections;

public class BeeCoin : MonoBehaviour {

    public int point;
    private float timeVida;
    public float tempoMaximoVida;

    private BeeCoinScore coin;

    AudioSource coinCollectSound;

    void Awake() {


        coin = GameObject.FindGameObjectWithTag ("BeeCoin").GetComponent<BeeCoinScore> () as BeeCoinScore;
    }

    // Use this for initialization
    void Start () {

        coinCollectSound = GameObject.Find("SpawnControllerBeeCoin").GetComponent<AudioSource>();

    }

    void OnCollisionEnter2D(Collision2D colisor)
    {
        if (colisor.gameObject.CompareTag ("Bee")) {


            coinCollectSound.Play ();

            coin.AddBeeCoinScore (point);
            Destroy (gameObject);
        }

        if (colisor.gameObject.tag == "Floor") {
            Destroy (gameObject, 1f);
        }
    }

}

My UI canvas МАГАЗИН Это довольно просто, у него есть 4 скина, связанных с изображениями, с ценой: 100, 200, 300 и 400 монет, 4 кнопки для покупки под каждым изображением и кнопка для выхода.

С#, если можно.


person Alan Vieira Rezende    schedule 05.05.2016    source источник
comment
Я не уверен, как вы написали игру, если вы не знаете, как создать систему разблокировки. if(coins >= skinCost) {unlockSkin(); coins -= skinCost; }   -  person BenVlodgi    schedule 05.05.2016
comment
Я пытаюсь beeCoin = PlayerPrefs.GetInt(highScoreKey, 0); if (beeCoin >= price) { Debug.Log("Need more coins!");} if (beeCoin >= price) {addSkin();Debug.Log("Skin ADDED"); beeCoins -= price;} но безуспешно...   -  person Alan Vieira Rezende    schedule 05.05.2016
comment
у вас есть один и тот же оператор if дважды подряд if (beeCoin >= price)... первый должен быть if (beeCoin < price)   -  person BenVlodgi    schedule 06.05.2016


Ответы (1)


Я решаю свою проблему.

На кнопку "купить" прикрепил скрипт BuySkin

А скрипт BeeCoinScore я добавил TakeBeeScore, удалил: if (coin> current Coin) {}, в пустоту OnDisable

Теперь он работает отлично.

Скрипт BuySkin.

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


    public class BuySkin : MonoBehaviour {

        public int price;

        public void OnClick()
        {
            if (BeeCoinScore.coin >= price) {

                BeeCoinScore.coin -= price;
                Debug.Log ("New skin added");
            }

            if (BeeCoinScore.coin < price) {

                Debug.Log ("Need more coins!");
            }
        }
     }

Скрипт BeeCoinScore.

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

     public class BeeCoinScore: MonoBehaviour
      {

       public static BeeCoinScore instance;
       public static int coin = 0;  
       public int currentCoin = 0;
       string totalCoinKey = "totalCoin";

       Text CoinScore; // Reference to the Text component.


       void Awake ()
       {
       // Set up the reference.
       CoinScore = GetComponent <Text> ();

       }
       public void Start(){

       //Get the highScore from player prefs if it is there, 0 otherwise.
       coin = PlayerPrefs.GetInt(totalCoinKey, 0);    
       }
       public void AddBeeCoinScore (int _point) {

       coin += _point;
       GetComponent<Text> ().text = "Bee Coins: " + coin;

       }

       public void TakeBeeCoinScore (int _point) {

       coin -= _point;
       GetComponent<Text> ().text = "Bee Coins: " + coin;

       }


       void Update ()
       {
       // Set the displayed text to be the word "Score" followed by the score value.
       CoinScore.text = "Bee Coins: " + coin;
       }


       void OnDisable(){

       PlayerPrefs.SetInt(totalCoinKey, coin);
       PlayerPrefs.Save();

    }
}
person Alan Vieira Rezende    schedule 07.05.2016