Virtual Currency Shop Tutorial – Part 2 (Code)

This post contains all the code that’s been written in the YouTube video.

You can read it at your own pace, although watching the video prior to looking at this code example is recommended.

 

ShopManagerScript.cs

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

public class ShopManagerScript : MonoBehaviour {

    [SerializeField]
    private Transform[] shopBtns;

    public Text CoinsTxt, SelectedItemTxt;
    public Color SelectedColor, NonSelectedColor;

    private int prevSelectedIndex;

    private void Start()
    {
        for (int i = 0; i < shopBtns.Length; i++)
        {
            shopBtns[i].GetChild(0).GetComponent<Text>().text = Inventory.Items[i].Name;
        }

        UpdateUI();
    }

    public void BuyOrSelectItem(int index)
    {
        if (Inventory.Items[index].Bought)
            Inventory.Instance.SelectItem(index);
        else
            Inventory.Instance.BuyItem(index);

        UpdateUI();
    }

    private void UpdateUI()
    {
        CoinsTxt.text = "Coins: " + Inventory.Coins.ToString();
        SelectedItemTxt.text = Inventory.Items[Inventory.SelectedItemIndex].Name;

        shopBtns[prevSelectedIndex].GetComponent<Image>().color = NonSelectedColor;
        shopBtns[Inventory.SelectedItemIndex].GetComponent<Image>().color = SelectedColor;

        prevSelectedIndex = Inventory.SelectedItemIndex;
    }
}

 

About the author 

Matt Rešetár

Matt is an app developer with a knack for teaching others. Working as a Flutter Developer at LeanCode and a developer educator, he is set on helping other people succeed in their Flutter app development career.

You may also like

Flutter UI Testing with Patrol

Flutter UI Testing with Patrol
  • hy mr resocoder. would you help?
    i have big a problem in my game.. i have many scenes, many characters and a scene shop. but how to declare the character in the shop to apply in many scenes when i selected a character in the scene shop..
    please help me

  • Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >