This section provides a simple example of creating a UI-Panel with 2 UI-Buttons and UI Text to allow selection of items to purchase.
The images below show how to configure the UI-Panel by adding UI-Buttons as children, and a UI text element to give details about the purchase.
The BuyItem script has public methods that can be configured to be executed by a UI-Button in the inspector.
In order for a method to be configured to be executed by a Button, it can not have more than 1 input parameter, so in this case, by defining the method to accept a string, then logic in the BuyItem script could determine what is purchased. Using a Switch-case statement simplifies the logic, but nested if-else logic could also be used. The case: "robot", case: "Robot" provides a way to allow either spelled version to be considered a match. When the case "robot" is matched, then the GameData.Score value is checked to see if there are enough funds to purchase the robot. Similar to the case for Plasma.
Important: Note that when using a string value in the inspector, you should not use quotation marks.
The logic in Start( ) checks to see if the key "RobotState" has value "companion" , if that is true, then the Robot Purchase Button is deactivated.
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;//to be added to a store panelpublicclassBuyItem:MonoBehaviour{string newLine =System.Environment.NewLine; [SerializeField]Text displayText; [SerializeField]Button robotBtn, plasmaBtn;voidStart() {displayText.text="Purchase Items"; //disable robot button if Robot is already a companionif( GameData.instanceRef.GetChoice("RobotState") =="companion") {robotBtn.gameObject.SetActive(false); //disable robot button } }publicvoidPurchaseItem(string itemName) {int funds =GameData.instanceRef.Score;switch (itemName) {case"Robot":case"robot":if( funds >=50) { GameData.instanceRef.Buy(50);displayText.text="Robot Purchased "+ newLine +"Score: "+GameData.instanceRef.Score;GameData.instanceRef.SaveChoice("RobotState","companion"); //set Robot as CompanionGameData.instanceRef.SaveChoice("LucyState","growth"); //set LucyStaterobotBtn.gameObject.SetActive(false); //disable robot button }else {displayText.text="Insufficient Funds, your account has: "+GameData.instanceRef.Score; }break;case"Plasma":case"plasma":if( funds >=25) {GameData.instanceRef.Buy(25);GameData.instanceRef.BoostHealth(20);displayText.text="Plasma Purchased, Health is : "+GameData.instanceRef.Health+ newLine +"Score: "+GameData.instanceRef.Score; }else {displayText.text="Insufficient Funds, your account has: "+GameData.instanceRef.Score; }break;default:displayText.text="Your account balance is "+GameData.instanceRef.Score;break; } }}