Purchasing upgrades

Now that we have the shop menu up and working, let's add in the functionality to purchase things:

  1. Go to the Hierarchy tab and then toggle the ShopMenu back on and delete all of the other buttons except for one which will be our reference for others.

    We will want each button to have three texts—the name of the object, the number we have, and the cost to build another.

  2. First, change this object's name to Desc and change the Text component's Alignment to the left horizontally, then duplicate it (Ctrl+D) name the duplicate Cost and center it. Finally, duplicate once more and change the name to Qty and put it on the right. Fill in the values if you'd like, but we'll be replacing the contents via code shortly:
    Purchasing upgrades
  3. Select the Button object and create a new C# Script named StoreItem and open the script up in your IDE. Once opened, use the following code:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI; // Text
    
    public enum ItemType
    {
        ClickPower, PerSecondIncrease
    };
    
    public class StoreItem : MonoBehaviour
    {
        [Tooltip("How much will this upgrade cost.")]
        public int cost;
    
        public ItemType itemType;
    
        [Tooltip("If purchased, how much will it increase this")]
        public float increaseAmount;
    
        private int qty;
    
        public Text costText;
        public Text qtyText;
    
        private GameController controller;
        private Button button;
    
        // Use this for initialization
        void Start ()
        {
            qty = 0;
            qtyText.text = qty.ToString();
            costText.text = "$" + cost.ToString();
    
            button = transform.GetComponent<Button>();
    
           // Execute the ButtonClicked function when we click 
           // the button
            button.onClick.AddListener(this.ButtonClicked);
    
           // Get a reference to our GameController via code
           controller = GameObject.FindObjectOfType<GameController>();
        }
    
        private void Update()
        {
            button.interactable = (controller.Cash >= cost);
        }
    
        public void ButtonClicked()
        {
            controller.Cash -= cost;
            switch (itemType)
            {
                case ItemType.ClickPower:
                    controller.cashPerClick += increaseAmount;
                    break;
                case ItemType.PerSecondIncrease:
                    controller.CashPerSecond += increaseAmount;
                    break;
            }
    
            qty++;
            qtyText.text = qty.ToString();
        }
    }

As before, let's dive into the new parts and then jump into an overall explanation as to what the code is doing.

Working with enumerations

At the top of this below the using statements, we make use of the enum keyword. Sometimes in code, we want to have a property that is used for a certain purpose, but it can be one and only one of a number of things.

For instance, if I'm having pizza for lunch, it can be in the oven cooking, on my plate, or in my mouth, but it can only be in one of those at a time.

We could use boolean values for each of these possibilities, switch one to true and the rest to false, but it's a hassle. We can also use an integer to store a number and then do different things based on a number, but then someone can put in any random number and you'd have to account for that. Instead, we create a new data type that can only have certain values for it. So in this case, ItemType can either be ClickPower or PerSecondIncrease but nothing else. Later on, you'll note that there will now be a variable of type ItemType in the class itself which we then use in the code to do something based on that value. This also makes it easier to create new types of item in the future as it'll require minimal changeut https://msdn.microsoft.com/en-us/library/sbbt4032.aspx.

Switch statements

This may be the first time that has seen a switch statement before. A switch statement can be thought of as a nice way to compare a single variable against a number of different values. In this case, the switch statement mentioned previously could be rewritten as:

if (itemType == ItemType.ClickPower)
{
    controller.cashPerClick += increaseAmount;
}
else (itemType == ItemType.PerSecondIncrease)
{
    controller.CashPerSecond += increaseAmount;
}

This may not seem like a big deal with this simple example, but when we get to Chapter 6, we will be using a switch statement again and it'll be more apparent why switch statements are such a nice thing to use.

Note

For those of you with a programming background, in C# you are required to put a break at the end of each case so fall-throughs are not possible by default.

Explaining the StoreItem class

As before, we've created a number of variables for us to work with, including references to text objects, which we then set whenever a value changes. Our items have a cost that the player has to pay to purchase them, and we can own more than one of them so we store how many have been purchased in the past.

The button's interactable property tells the UI system if the player can click on the button or not. In our case, we don't want the player to be able to buy anything unless they have enough money to purchase it, so in our Update function, we set the value to true if the player has enough money and false if not.

Finally, if the player clicks on the button and it is valid, then ButtonClicked will get called, which will alter a certain value based on the value of our item's type.

Note

Note the use of the AddListener function, which allows us to add a function to be called whenever a UnityEvent is executed. For more information on that, check out http://docs.unity3d.com/ScriptReference/Events.UnityEvent.AddListener.html.

Filling in Item descriptions

Now that we have the functionality built in for the buttons, let's see how we can use them within the editor!

  1. Save your script. Now back in the editor, attach the script to our Button object. In our newly added component, attach the Cost and Qty texts to the respective objects. Next, change the Cost to 5, set the Item Type to Per Second Increase, and change the Increase Amount to 0.1. Finally, select the Desc object and change the text to Hire Code Monkey.
  2. Next, duplicate the button and then change the Desc text to Develop Game and then from the Button object, go to the Store Item component, change the Cost to 50, the Item Type to Click Power, and the Increase Amount to 1:
    Filling in Item descriptions
  3. Finally, disable the ShopMenu object, save your scene, and start the game!
    Filling in Item descriptions

Now we have buttons that work for each of the types of thing that we can increase!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset