Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

how to buy different player with in game coin scores

Discussion in 'Scripting' started by yariangames2016, Dec 4, 2016.

  1. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    i have few player in my game , i need after getting sufficient amount of score coins , player of game can unlock other locked players, any help ?
     
    adee11 likes this.
  2. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    create a script that stores an Int value called coins. Then when ever they player does something good, add to the coins int.

    you need a menu or store system to display a available things to buy. If the player chooses to buy it, remove from the coins int
     
  3. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    it is hard to understand for me your explanation . i have a game manager script in which i have score int variable available. whenever player in game gets coins , this score variables counts up . i have some ui buttons which presents my other players to get bought . this is the question , how to check if player has enough score to buy one of those other players ? can you please show your idea with sone ground codes . thanks .
     
  4. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    if(playerCoin >= price of item)
    {
    allow purchasse
    }
     
  5. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    to which game object should i attach this code?
     
  6. BravenBitSoftware

    BravenBitSoftware

    Joined:
    Feb 26, 2014
    Posts:
    56
    You will need to make different scripts. I have never did this, but i am going, so i think what you need to do is similar.
    The player will get points eventually, right? You must have a script that will add points to the player each time he does something. What you need to do, is make a script that will have an int/float (you decide) in which it will store the player's points. Then you need to make another script that will hold the thing you want to buy, like another character. In this script, you will need to specify the amount of points the player will need to buy determined thing, and check if he have enough points, then he can buy it.
     
  7. radicalEd

    radicalEd

    Joined:
    Mar 19, 2016
    Posts:
    81
    This is something that is pretty simple, but also extremely implementation based.

    If you cannot write this yourself then you need to familiarize yourself with C# / JavaScript. I would suggest reading their documentations.
     
  8. Lord-Smingleigh

    Lord-Smingleigh

    Joined:
    Jan 23, 2013
    Posts:
    10
  9. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    Thanks all of you friends but what i want to do is like bryangs told .i have playerA which has a script attached to in gameplay scene .also in shop scene i have playerB and playerC and playerD . at first only playerA is unlocked and is playable .but i need when i have 1000 score obtained i buy playerB . in shop scene i have a script attached to a game object for saving and showing current score with a ui text . in this scene i have a list of game objects which present playerB ::: playerD , Here i need to address current obtained amount of score ,,,that is it possible to buy new player or not .
    if somebody with codes show that , it is all useful .
    thanks .
     
  10. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    What script is keeping track of if the character has been purchased or not?
    I might do this with a bool attached to each character. pubic bool isPurchased;

    Then you're store script has to read this bool. If bool is false then allow to purchase for 1000 coins. If bool is true then allow character to be used.

    The main problem with your post is we don't have all he info to give you direct answers.
     
  11. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    I can tell you exactly how, as I already have done this exact same thing in my game (C#):
    We want the money being universal, the same in all scenes, the same for everywhere, if you change it in Scene A, it will be changed in all other scenes too. How to do this? pretty simple.

    1.- Create a new C# script and name it GlobalValues, cause we will use it later, then, you will find:
    Code (CSharp):
    1. public class GlobalValues : MonoBehaviour
    make it a static:
    Code (CSharp):
    1. public static class GlobalValues : MonoBehaviour
    As it is static, you dont need to create a gameObject in every scene to carry it. It runs alone, (EDIT: so you wont need : MonoBehaviour).

    Add a public static float named "money":
    Code (CSharp):
    1. //public class SpriteHolder : NetworkBehaviour {
    2.     //public static float money;
    3. //} Sorry I missed this, IGNORE THIS PART IN //s, Use the one below
    4. //Its just that I made a small mistake and... well It was 3 days ago, dont remember
    5. //what I did but, well Ignore that above, use the one below
    6.  
    7. public  static class GlobalValues {
    8.     public static float money;
    9. }
    10.  
    There you go, you got an universal money value.

    I dont know how exactly your game is, but I am pretty sure the shop is in another scene, Id recommend to do a 2D shop, so you can use buttons from UI and it will look good, this is a bit weird in 3D, well thats your choice. well, you should open GlobalValues and add one more public static int:
    Code (CSharp):
    1. public static int character
    additionally, one public static bool for every unlockable character:
    Code (CSharp):
    1. public static bool character2Unlocked;
    2. public static bool character3Unlocked;
    3. public static bool character4Unlocked;
    4.  
    Now, here is an image of how you could do the interface (2D):


    This is how it would look, I dont know what yout game is about so i made one version, as you can see there is an exit button, the characters, and in case you have more characters than those who fit the screen you add next page and prevous page buttons.

    With your shop built, then we proceed to the next step, you add a button below each character.

    Then you make the following C# script, named BuyScript:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI; //Lets you use UI stuff
    4.  
    5. public class BuyScript : MonoBehaviour {
    6.  
    7.     public int myChar; //Number assigned manually for the character number.
    8.     private float price; //The price
    9.  
    10.     public Text text; //Where the price is displayed, that will change
    11.                       //to select and selected when already unlocked
    12.  
    13.     void Start() {
    14.         price = GetComponent<BuyScript2>().price; //Will be marked as an error now as
    15.                                                                                //There is no BuyScript 2 YET
    16.  
    17.     void Update()
    18.     {
    19.         if (myChar == 1) //If its the first character
    20.         {
    21.             if (GlobalValues.character == 1) //If character is 1
    22.             {
    23.                 text.text = "selected";  //Changes the text to "Selected", as
    24.                                          //It is character 1 and GlobalValues.character
    25.                                          //is also 1.
    26.             }
    27.             else //If its not character 1
    28.             {
    29.                 text.text = "select"    //Changes the text to select
    30.             }
    31.         }   //Note that character one is the one you start with, so has no buy stuff.}
    32.  
    33.         if (myChar == 2) //If its the second character
    34.         {
    35.             if (GlobalValues.character2Unlocked) //If it has been unlocked
    36.             {
    37.                 if (GlobalValues.character == 2) //If character is 2
    38.                 {
    39.                     text.text = "selected";  //Changes the text to "Selected", as
    40.                                              //It is character 2 and GlobalValues.character
    41.                                              //is also 2.
    42.                 }
    43.                 else //If GlobalValues.character is not  2
    44.                 {
    45.                     text.text = "select"    //Changes the text to select, cause it isnt selected
    46.                 }
    47.             }
    48.             else  //If it hasnt been unlocked
    49.             {
    50.                    text.text = "$" + price; //Sets the text to display the price.
    51.             }
    52.         }
    53.         //The same code of myChar 2 for every single other character, but changint
    54.         //the number 2 to the number of character
    55.     }
    56. }
    57.  
    This script only checks:
    - If you have bought the character
    - If you have selected the character

    Now lets make the one that buys/selects the character, name it BuyScript2:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BuyScript2 : MonoBehaviour {
    5.  
    6.     private int myChar; //This time there is no need to assign this one
    7.     public float price; //Price, manually set in the inspector
    8.  
    9.     void Awake() //This is run even if the script is off
    10.     {
    11.         myChar = GetComponent<BuyScript>().myChar;
    12.         //Sets this myChar value to the one in BuyScript,
    13.         //So you dont have to set it twice.
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         if (myChar == 1) { GlobalValues.character = 1; } //Selects Char 1 if it
    19.                                                          //this is char 1 button.
    20.  
    21.         if (myChar == 2) //If This is Character 2 button
    22.         {
    23.             if (GlobalValues.character2Unlocked) //If you have unlocked character 2
    24.             {
    25.                 GlobalValues.character = 2; //Selects character 2
    26.             }
    27.             else  //If you havent unlocked character two
    28.             {
    29.                 if (GlobalValues.money >= price) //If you have greater or equal money than the price
    30.                 {
    31.                     GlobalValues.money = GlobalValues.money - price; //Substracts the price from
    32.                                                                      //your money
    33.                 }
    34.                 //If you dont have greater or equal money than the price nothing happens.
    35.             }
    36.         }
    37.  
    38.         //And the same for every other character, changing the instances of 2.
    39.  
    40.        GetComponent<BuyScript2>().enabled = false; Turns the script off AT THE END
    41.     }
    42. }
    43.  

    We have the scripts, time to config them in the inspector.
    Nothing better than an image to explain it simple and fast

    You can see that each button has BuyScript and BuyScript 2, with their respective values, also have their own text component, attached to the BuyScript and the most important: BuyScript2 is not enabled.

    Here is an image of the Button Component Stuff:

    Remember that this button component is in BuyButton1, BuyButton2's enables its own BuyScript2.

    At this moment, it is working, this setup lets you buy new characters and select the ones you already unlicked, but they keep showing the locked character image :p.

    Now lets make them "Unlock" in the image too:

    The following script goes attached to the characters images not their Buy Button.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI; //This one needs UI
    4.  
    5. public class unlockedScript : MonoBehaviour {
    6.     public int myChar;
    7.     public Sprite char2;
    8.     public Sprite char3;
    9.     public Sprite char4;
    10.     private bool changed;
    11.  
    12.     void Update()
    13.     {
    14.         if (changed == false) //If it hasnt changed the sprite
    15.         {
    16.             if (GlobalValues.character2Unlocked && myChar == 2) {  //If you have unlocked Char2 and this is Char2 Image
    17.             GetComponent<Image>().sprite = char2; //Changes to unlocked Char2 Image
    18.             changed = true;
    19.             }
    20.             if (GlobalValues.character3Unlocked && myChar == 3) {
    21.             GetComponent<Image>().sprite = char3;              //The same but with Char 3
    22.             changed = true;
    23.             }
    24.             if (GlobalValues.character4Unlocked && myChar ==4) {
    25.             GetComponent<Image>().sprite = char4;               //The same but with Char 4
    26.             changed = true;
    27.             }
    28.             //And so on for every character you have
    29.         }
    30.     }
    31. }
    32.  
    This has nothing to do about the problem, but I really wanted to draw the unlocked character versions:

    Well, when you already bought the character, you dont really want to have a red button displaying "Selected" or "Select", to do this we go back to "BuyScript", and add the following:
    At the beginning:
    Code (CSharp):
    1. public Image image;
    *This one is the image of the button, assigned in the inspector.

    In the code for every character:
    Code (CSharp):
    1.         if (myChar == 2) //If its the second character
    2.         {
    3.             if (GlobalValues.character2Unlocked) //We already have this part of the code
    4.             {
    5.                 if (GlobalValues.character == 2)
    6.                 {
    7.                     text.text = "selected";
    8.                     image.color = Color.green; //We add this one
    9.                 }
    10.                 else //If its not character 2
    11.                 {
    12.                     text.text = "select"
    13.                     image.color = Color.cyan; //We add this one
    14.                 }
    15.             }
    16.             else  //If it hasnt been unlocked
    17.             {
    18.                    text.text = "$" + price; //Sets the text to display the price.
    19.                    image.color = Color.red; //Not really necesary, but there is nothing to loose
    20.             }
    21.         }
    If you instead want to change to a different sprite instead of a color when bought, tell me to add a Sprite version, as I dont think you will actually want to change sprite, I dont see the need to give an example.

    Hope this helps :)
     
    Last edited: Dec 19, 2016
    KakarotoSoft, zeen0 and adee11 like this.
  12. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    but in picture it is enabled,why?
     
  13. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    There are two BuyScripts, one always enabled and the otherone only enables for a single frame, the one enabled is BuyScript, only BuyScript, the one not enabled is BuyScript2, and is below. The picture shows correctly.

    The reason for this, is that the one always enabled, changes the text, and it doesnt matter to repeat every frame, while the one that only enables when the button is clicked is the one that buys the character, if it was enabled always, then as you enter the shop, if you have enough money every character you can buy with your current money will buy automatically, without asking, and between the ones you already have will be selected every frame.
     
  14. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    If you want a sign to display your money, the line is simple: (You need at the start of the script Using.UnityEngine.UI; and a Text Component attached to the gameObject).
    GetComponent<Text>().text = "Your Money: " + GlobalValues.money;

    Note that space after the : cause if you erase it, the money will apear as "Your Money:100", else it will appear as "Your Money: 100", I think is nicer with the space, but do it as you like it.
     
  15. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    when i run my game , when i click on character 1 , it says selected . when i click on any other player to buy , simply no things goes on. also i have already a ui text to show current obtained score. how can i get obtained score from gameplay scene and show that score with this ui text ? and after that to compare if this score is enough to buy locked character?thanks .
     
  16. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    Make a new code, attach it to the text that shows the current score and use the inspector to set the public text:
    Code (CSharp):
    1. Using.UnityEngine;
    2. Using.System.Collections;
    3. Using.System.Collections.UI;
    4.  
    5. public class ShowScoreText : MonoBehaviour {
    6.       public Text scoreText;
    7.  
    8.       void Update() {
    9.             scoreText.text = "Your score is: " + GlobalValues.money;
    10.       }
    11. }
    Also to change your score easily, you can open GlobalValues and do the following:
    Code (CSharp):
    1. public static float money = 1000;
    The 1000 value is whatever you like, enough to buy the character you want to test funcionalitiy for
     
  17. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    i did like you said,now ui text shows current money which is 1000 . but when i click on one player to buy and unlock it , nothing again goes on ! strange !!! what have i done wrong , you think?

    i attached BuyScript and BuyScript2 to every button that i have for buying different characters.

    i dargged button1 from Hierarchy to On Click slot and then i chose BuyScript2 and then bool enabled . after that i checked to make it active . i repeated this step for all of buttons.
     
    Last edited: Dec 20, 2016
  18. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    Hmph, Try to send a pic of the components and the script BuyScript2, if we cant solve the problem this way, I will make a video and send it to you.
     
  19. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
  20. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    Ok, if that does not work, Im starting the video xd
     
  21. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    Hi, i am waiting for your video and thanks. when normally you visit here in forum ? have you any skype or whatsapp? i like to be in touch with you .
     
  22. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    Video is uploading, 44 minutes xd xD, I visit the forum normally when I have my computer, cause lately Ive been having lots of work to do around the house, but about January 2nd Ill be free to be here kinda the whole day lol. until school starts.

    Its goin 2 take a while.

    I dont have skype neither WhatsApp, but you cant find me on Steam under the name "gunging"
    Code (CSharp):
    1. If you are searching me in steam, is easier to find me going to Terraria guides and searching for my Guide "How to Throw Tetra Flame Knives" cause its good rated and theres only one in the world, while there are two gungings more
     
  23. yariangames2016

    yariangames2016

    Joined:
    Sep 29, 2016
    Posts:
    78
    i dont know how to use Steam ! But here we can sometime talk together . i am so happy and keen to see your video!!!
    XD :)
     
  24. KakarotoSoft

    KakarotoSoft

    Joined:
    Oct 18, 2017
    Posts:
    1
    Hi! can you finally solve the problem?
    I am also trying to use this method..
    How to assign the character to the button?
     
    Last edited: Apr 17, 2018
  25. Gunging

    Gunging

    Joined:
    Sep 6, 2016
    Posts:
    139
    I made that script like a year ago when I was relatively new at programming. I have seen it and now I realize how basic it is. I've written this new one that requires only 1 script for it all to work and is completely fool-proof. It, however, can get very complex, more especifically in the two dimensional array it uses, so I might have to make a video to explain it, I tried though in comments.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. [RequireComponent(typeof(PolygonCollider2D))]
    7. public class ShopScript : MonoBehaviour
    8. {
    9.  
    10.     [Header("Currency Settings")]
    11.  
    12.     ///The money the player has.
    13.     ///This is constant throughout the scenes.
    14.     [Tooltip("The money the player has.")]
    15.     public static float money;
    16.  
    17.     ///The symbol of the currency
    18.     ///For example "$",
    19.     ///Leaving blank is acceptable.
    20.     [Tooltip("(Optional) The symbol of the money. E.g., $.")] public string currencySymbol;
    21.  
    22.     ///Will the currency symbol be a prefix or a suffix?
    23.     ///Example of Prefix: $4000
    24.     ///Example of Suffix: 4000$
    25.     ///Setting this as "false" means it will be a suffix.
    26.     ///If you don't have a symbol just ignore this.
    27.     [Tooltip("Ignore if you don't have a currency symbol.")] public bool currencySymbolIsPrefix;
    28.  
    29.  
    30.  
    31.     [Space]
    32.     [Header("The Components of the Shop Itself")]
    33.  
    34.     ///The great "Buy" button.
    35.     ///Whether or not the player has enough money to buy something is not important here.
    36.     ///If the player has enough money or not is detected somewhere else, this is just to know what button is the BUY button.
    37.     [Tooltip("Button that when pressed triggers buying.")]
    38.     public Button buyButton;
    39.  
    40.     ///The image of the Buy Button.
    41.     ///Optional but Recommended.
    42.     [Tooltip("The image of the Buy Button")] public Image buyButtonImage;
    43.  
    44.     ///The place where you want to show the player how much money they have.4
    45.     ///It is Optional but heavilly recommended.
    46.     [Tooltip("(Optional) The text that will display how much money the player has.")] public Text moneyDisplayText;
    47.  
    48.     ///The text that tells the player that the number displayed in the moneyDisplayText is their money.
    49.     ///This is optional, a common example would be "You have:"
    50.     ///This example will display the money of the player in the form "You have: $4000"
    51.     ///Optional but recommended.
    52.     [Tooltip("(Optional) The text that will introduce the amount of money the player has.\nE.g., \"You have:\"")] public string moneyDisplayIntroductoryText;
    53.  
    54.     ///The button to go to the next item.
    55.     ///It is optional if you only have 1 item in your shop... unlikely.
    56.     [Tooltip("The button to display the next item in the shop")] public Button nextItemButton;
    57.  
    58.     ///The button to go to the previous item.
    59.     ///It is optional if you only have 1 item in your shop... unlikely.
    60.     [Tooltip("The button to display the previous item in the shop")] public Button previousItemButton;
    61.  
    62.     ///The text that tells if the current item is Selected, Bought, Not Bought or Locked.
    63.     ///This defines what the BUY button will do when it is pressed.
    64.     ///SELECTED means the item is equipped.
    65.     ///SELECT means the item has been bought but is not equipped.
    66.     ///BUY means the item can be bought.
    67.     ///LOCKED means you can't buy it (Because you don't have enough money).
    68.     ///
    69.     ///It is not uncommon for the Status Text to be the same as the Buy Button's Text (Recommended by me!)
    70.     [Tooltip("The text that shows the status of the current displayed item. \n(If it is Selected, Bought, Not Bought or Locked)")] public Text itemStatusDisplay;
    71.  
    72.     ///This image will show a picture of the item.
    73.     ///Optional but heavily recommended.
    74.     [Tooltip("The image that will show the item.")] public Image itemDisplay;
    75.  
    76.     /// This will display the name of the item.
    77.     /// Optional but heavily recommended.
    78.     [Tooltip("The text that will display the name of the item.")] public Text itemNameDisplay;
    79.  
    80.     /// This will display the cost of the item.
    81.     /// The cost will include the money symbol if you chose any.
    82.     /// Optional but heavily recommended.
    83.     //Important Notice:
    84.     //If this is the same as itemStatusDisplay, the item will display its cost instead Of "LOCKED" when it can't be bought, and "BUY: [PRICE]" When you can buy it:
    85.     //Doing this is extremely recommended!
    86.     [Tooltip("This will display the cost of the item.")] public Text itemCostDisplay;
    87.  
    88.     /// Will display how many you have of a consumable.
    89.     /// Because you usually want to know how many Tribal Discs you already have
    90.     [Tooltip("Will display how many you have of a consumable.")] public Text itemCountDisplay;
    91.  
    92.     ///Texts that displays the features you would like to show about the item
    93.     ///You can have as many as you want.
    94.     ///E.g. Your item can have a "Attack Damage" value, "Durability" and/or an "Armor Points" value.
    95.     ///Then you make the size of this array a two, and assign both Text components in the inspector.
    96.     ///They will display their value separately. Isn't that awesome?
    97.     ///Optional
    98.     [Tooltip("Texts that displays the features you would like to show about the item")] public Text[] itemFeatureTexts;
    99.  
    100.     ///This is the name of the values displayed by itemFeatureTexts texts.
    101.     ///E. g. "Attack Damage", "Durability", and "Armor Points"
    102.     ///Then, the first itemFeatureText will display the Attack Damage, and the second the Durability...
    103.     ///This is Optional if you have no itemFeatureTexts.
    104.     [Tooltip("The names of the values.")] public string[] itemFeatureNames;
    105.  
    106.     ///The style of FEature Names.
    107.     ///E. g. You want one of the features to be a description instead,
    108.     ///then you want it to be, for example, italics.
    109.     ///Thus you set the correspoinding value to "Italics". Voila!
    110.     [Tooltip("The style of Feature Names")] public FontStyle[] styleOfFeatureNames;
    111.  
    112.     ///The type of Features.
    113.     ///Set as 0 for Numebrical, and 1 for statement.
    114.     ///E.g. "Attack Damage", "Durabilty" and "Armor Points" are numerical, so you set their correspoding int to 0.
    115.     ///THis will list them as: "Attack Damage: 20" Depending on the value they are assigned for any item.
    116.     ///However, lets say you had another feature "Fire Resistant" or a lore line "An ancient relic".
    117.     ///Something as "Fire Resistant: 1" sounds almost acceptable, but "An ancient relic: 28" is dumb, then you set their int to 1.
    118.     ///Then they will only be listed as "Fire Resistant" and "An ancient relic", without the numerical value.
    119.     [Tooltip("The type of Features. \nE.g. numerical (0), or statements (1).")] public int[] typeOfFeature;
    120.  
    121.  
    122.  
    123.     [Space]
    124.     [Header("Item Configurations")]
    125.  
    126.     ///In order, the names of the items.
    127.     ///E. g. "Ancient Sword"
    128.     [Tooltip("The names of the items.")]
    129.     public string[] itemNames;
    130.  
    131.     ///In order, the sprites of the items.
    132.     ///E. g. An image of an ancient sword.
    133.     [Tooltip("The images of the items.")] public Sprite[] itemImages;
    134.  
    135.     ///In order, the costs of the items.
    136.     ///E. g. 4000
    137.     [Tooltip("The costs of the items.")] public float[] itemCosts;
    138.  
    139.     ///What is this? Polygon Collider 2D? Wot?
    140.     ///
    141.     ///---------------THE REASON----------------
    142.     ///You see, Each item has its own list of Feature values, so a simple Array wasn't enough.
    143.     ///What I needed is an ARRAY of ARRAYS of FLOATS (woah).
    144.     ///However Unity does not support pubilic float[][].
    145.     ///BUT the Polygon Collider 2D has an array of arrays, that I am exploiting...
    146.     ///
    147.     ///----------------HOW TO USE----------------
    148.     ///The polygon collider you use should be disabled,
    149.     ///Then, You will notice there is a section called "Points"
    150.     ///In this there is a section called "Paths"
    151.     ///And each Path has its Array called "Element X"
    152.     ///Each Element has a configurable number of "Points"
    153.     ///
    154.     ///Think of it this way:
    155.     ///Each ELEMENT corresponds to your items.
    156.     ///Each POINT of each element corresponds to a feature of the item.
    157.     ///
    158.     ///Then, you set the number of Paths to 1
    159.     ///you set the size of ELEMENT 0 to the number of features you have.
    160.     ///Then, you set the number of Paths to the number of items you have.
    161.     ///
    162.     ///So, to give the Ancient Sword (Item #0) a "Durability" (Feature #1) value of "10":
    163.     ///You set the X-value of Element #1 (Durability) of the Path #0 (Ancient Sword) to 10.
    164.     ///
    165.     ///Ignore the Y-values of these things.
    166.     ///----------------------------------------------
    167.     ///
    168.     ///If you ever add a new feature, it is not necessary to update all the features.
    169.     ///Every unnassigned feature will be counted as "null" and not be listed for that particular item.
    170.     ///(Unnassigned meaning that the array has no value [Not even 0] for it)
    171.     //Now here is the interesting Part:
    172.     //If you set this value equal to nullFeatureNumber (Default is 0)
    173.     //Then the feature will not be displayed.
    174.     //So, if a sword has an "Armor Points" value of 0, the sword won't show any "Armor Points" value.
    175.     //The number of itemFeatureValues that don't have a value equal to nullFeatureNumber MUST be equal or lesser than the number of Item Feature Texts.
    176.     //
    177.     //For statement features, any value that is not the nullFeatureNumber will work, and just not be shown.
    178.     [Tooltip("The value of the features of the items. \nThis is too long to explain in a Tooltip,\n read the Variable description in the script.")] public PolygonCollider2D itemFeatureValues;
    179.  
    180.     /// In order, the Exclusiveness IDs of the items.
    181.     /// Set these to -1 if you don't get what they are.
    182.     /// You can't select two items with the same POSITIVE Exclusiveness ID
    183.     /// And you can buy an item endlessly if the ID is 0
    184.     /// Any negative (Less than 0) ID will be ignored for exclussiveness.
    185.     /// An ID of 0 will mean you can buy the item as many times as you can.
    186.     ///
    187.     /// You know, you can't use 5 swords at the same time, so you give them the same Positive Exclusiveness ID (Lets use 1 as example)
    188.     /// Then, when player selects a sword, all the other swords will be unselected.
    189.     /// Thus the player can only have 1 sword equipped at the same time.
    190.     ///
    191.     /// You also want to be able to buy, for example, Food more than once
    192.     /// Then you will set the ID to 0 so it never becomes "Selected" or even "Bought"
    193.     ///
    194.     /// Any negative Id will make the items Buyable only once and non-exclusive.
    195.     [Tooltip("The \'Exclusiveness ID\' of the items. \n Set all of these to -1 if you don't get what these are. \nAll items with the same POSITIVE ID will be exclusive among each others, \n\nE.g. You cant use 5 swords at the same time,\n so to every sword, you give the same POSITIVE exclusiveness ID, \nthen you only ever have 1 equipped at a time.")] public int[] itemExculsivenessIDs;
    196.  
    197.     //This will store what value each item will target when bought.
    198.     //The value that knows if you have the ancient sword equipped is usually not the same one that knows if you have the golden helmet equipped.
    199.     ///------------SETUP------------
    200.     //1) Create all your public static ints to store your variables.
    201.     //In my example, I have 4 Items:
    202.     //Golden Helmet (A helmet)
    203.     //Ancient Sword (A Weapon)
    204.     //Tempest (A Weapon)
    205.     //Tribal Disc (crafting ingredient)
    206.     public static int equippedHelmet, equippedWeapon, numberOfTribalDiscs;
    207.     //2) Go to Purchase() and edit accordingly.
    208.     /// 3) Go to GetEquipmentState() and edit accordingly.
    209.     //4) Set your variable IDs in the inspector for each of your items.
    210.     [Tooltip("You must set this value to your own configuration.")] public int[] itemEquipmentValues;
    211.  
    212.     /// To know if it is a consumable, if it is, it will tell you how many you have.
    213.     [Tooltip("To know if it is a consumable, if it is, it will tell you how many you have.")] public bool[] itemConsumableness;
    214.  
    215.  
    216.     [Space]
    217.     [Header("Misc Variables")]
    218.  
    219.     ///The number that will cause an item feature to not be listed.
    220.     ///An item feature is something like "Attack Damage", "Durability", "Armor Points"...
    221.     ///A sword will not have "Armor Points" (usually)
    222.     ///and a Chestplate will not have "Attack Damage" (usually)
    223.     ///so this nullFeatureNumber will make the Feature to not be listed (So armors don't list "Attack Damage" and Swords dont list "Armor Points")
    224.     [Tooltip("THe number that will cause a Feature to be ignored.")]
    225.     public float nullFeatureNumber;
    226.  
    227.     /// The size of this must be 4:
    228.     /// SELECTED being the first entry,
    229.     /// SELECT being the second,
    230.     /// BUY being the third,
    231.     /// LOCKED being the fourth.
    232.     /// If you don't want to use this feature, make the four colors WHITE (No tint at all).
    233.     [Tooltip("The tint of the Buy Button Image depending on status.")] public Color[] statusColors;
    234.  
    235.     /// Will update the item status every frame (kinda bad unless necessry)
    236.     // To know if its necessary:
    237.     // The only way it would be necessary is there being a way to earn money while in the shop scene.
    238.     [Tooltip("If there is no way you can earn money in the shop scene, leave this in false.")] public bool updateItemStatusConstantly;
    239.  
    240.     int currentShownItemID; //Item that is currently being shown.
    241.  
    242.     //This value stores all the items ever bought. You must set the length manually to the length of itemNames.
    243.     public static bool[] shopItemsBought = new bool[4];
    244.  
    245.  
    246.     private void Start()
    247.     {
    248.         UpdateMoney();
    249.         ShowItem(0);
    250.         itemFeatureValues = GetComponent<PolygonCollider2D>();
    251.         if (buyButton != null) { buyButton.onClick.AddListener(OnBuyButtonClick); } else { Debug.LogError("No Buy Button Assigned!"); }
    252.         if (nextItemButton != null) { nextItemButton.onClick.AddListener(OnNextPage); }
    253.         if (previousItemButton != null) { previousItemButton.onClick.AddListener(OnPreviousPage); }
    254.     }
    255.  
    256.     private void Update()
    257.     {
    258.         if (updateItemStatusConstantly) { UpdateItemStatus(); UpdateMoney(); }
    259.     }
    260.  
    261.     public void ShowItem(int itemID)
    262.     {
    263.         currentShownItemID = itemID;    //Updates the current shown item ID
    264.         if (currentShownItemID < itemImages.Length) { itemDisplay.sprite = itemImages[itemID]; }  //Updates the Displayed Image
    265.         if (currentShownItemID < itemNames.Length) { itemNameDisplay.text = itemNames[itemID]; }  //Udpates the Displayed Name
    266.         UpdateItemStatus();  //Well... Udpates the Status
    267.    
    268.         if (itemFeatureValues == null) { itemFeatureValues = GetComponent<PolygonCollider2D>(); }
    269.         if (itemID < itemFeatureValues.pathCount) {
    270.             bool[] usedFeatureTexts = new bool[itemFeatureTexts.Length];    //Creates an array of a size equal to the number of item feature texts.
    271.             bool[] setFeatures = new bool[itemFeatureValues.GetPath(itemID).Length];    //Creates an array of a size equal to the number of features the item has.
    272.  
    273.             for (int featureID = 0; featureID < itemFeatureValues.GetPath(itemID).Length; featureID++)
    274.             {
    275.                 float value = itemFeatureValues.GetPath(itemID)[featureID].x;   //Gets the value of the feature
    276.                 if (value != nullFeatureNumber)
    277.                 {   //If the value of the feature is not the Null Feature Value
    278.                     for (int featureTextID = 0; featureTextID < usedFeatureTexts.Length; featureTextID++)
    279.                     {
    280.                         if (!usedFeatureTexts[featureTextID] && !setFeatures[featureID])
    281.                         { //IF the feature text hasn't been used and the feature is not shown yet.
    282.                             usedFeatureTexts[featureTextID] = true; //Marks the feature text as 'used"
    283.                             setFeatures[featureID] = true;  //Marks this Feature as "shown"
    284.                             string displayValue = itemFeatureNames[featureID];  //Creates the value to display
    285.                             if (typeOfFeature[featureID] == 0)
    286.                             {    //If the feature is NUMERIC
    287.                                 displayValue = itemFeatureNames[featureID] + ": " + value;  //Assigns its numeric value to the name
    288.                             }
    289.                             else if (typeOfFeature[featureID] == 1)
    290.                             {   //If the feature is NOT NUMERIC
    291.                                 displayValue = itemFeatureNames[featureID]; //Leaves the value just as the feature name.
    292.                             }
    293.                             itemFeatureTexts[featureTextID].text = displayValue;    //Sets the text to the display value.
    294.                             itemFeatureTexts[featureTextID].fontStyle = styleOfFeatureNames[featureID]; //Changes the font style accordingly
    295.                         }
    296.                         if ((featureTextID == usedFeatureTexts.Length - 1) && !usedFeatureTexts[featureTextID])
    297.                         {   //If this is the last feature and the Feature text is unused
    298.                             itemFeatureTexts[featureTextID].text = "";  //It hides the feature text, else it would keep displaying the previous value (Of another item).
    299.                         }
    300.                     }
    301.                 }
    302.             }
    303.             for (int boolean = 0; boolean < usedFeatureTexts.Length; boolean++)
    304.             {
    305.                 if (!usedFeatureTexts[boolean])
    306.                 {
    307.                     itemFeatureTexts[boolean].text = "";
    308.                 }
    309.             }
    310.         }
    311.  
    312.     }
    313.  
    314.     void UpdateItemStatus()
    315.     {
    316.         if (currentShownItemID < itemConsumableness.Length && itemCountDisplay != null)
    317.         {   //If the ID is appropiate
    318.             if (itemConsumableness[currentShownItemID])
    319.             { //If its consumable
    320.                 itemCountDisplay.text = "You have: " + (GetEquipmentState(currentShownItemID)).ToString(); //Mentions the amount of these you already ahve.
    321.             }
    322.             else
    323.             { //If its not consumable
    324.                 itemCountDisplay.text = ""; //Hides the COunt Text.
    325.             }
    326.         }
    327.  
    328.         if (currentShownItemID < shopItemsBought.Length)
    329.         {   //If the ID is appropiate
    330.             if (itemCostDisplay == itemStatusDisplay)
    331.             { //If the Cost Display and the Status Display is the same thing.
    332.                 if (shopItemsBought[currentShownItemID] == true)
    333.                 {  //If it has been bought
    334.                     if (currentShownItemID < itemConsumableness.Length)
    335.                     {
    336.                         if ((GetEquipmentState(currentShownItemID) == 1) && !itemConsumableness[currentShownItemID])
    337.                         { //If it is equipped and is not consumable
    338.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "SELECTED"; }
    339.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[0]; }
    340.                         }
    341.                         else
    342.                         { //If it is not equipped
    343.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "BOUGHT"; }
    344.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[1]; }
    345.                         }
    346.                     }
    347.                 }
    348.                 else
    349.                 { //If it has not been bought (or is consumable)
    350.                     if (currentShownItemID < itemCosts.Length)
    351.                     {
    352.                         if (money >= itemCosts[currentShownItemID])
    353.                         { //If you have enough money to buy.
    354.                           //Because the Cost Display and Status Display is the same thing, it displays "Buy" and the cost.
    355.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "BUY\n" + RefinedMonetaryValue(itemCosts[currentShownItemID]); }
    356.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[2]; }
    357.                         }
    358.                         else
    359.                         { //If you are too poor to buy
    360.                           //Because the Cost Display and Status Display is the same thing, it displays "Locked" and the cost.
    361.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "LOCKED\n" + RefinedMonetaryValue(itemCosts[currentShownItemID]); }
    362.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[3]; }
    363.                         }
    364.                     }
    365.                 }
    366.             }
    367.             else
    368.             { //If the Cost Display and the Status Display are NOT the same thing.
    369.                 if (shopItemsBought[currentShownItemID] == true)
    370.                 {  //If it has been bought
    371.                     if (currentShownItemID < itemConsumableness.Length)
    372.                     {
    373.                         if (GetEquipmentState(currentShownItemID) == 1 && !itemConsumableness[currentShownItemID])
    374.                         { //If it is equipped and is not consumable
    375.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "SELECTED"; }
    376.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[0]; }
    377.                             if (itemCostDisplay != null) { itemCostDisplay.text = ""; }
    378.                         }
    379.                         else
    380.                         { //If it is not equipped
    381.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "BOUGHT"; }
    382.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[1]; }
    383.                             if (itemCostDisplay != null) { itemCostDisplay.text = ""; }
    384.                         }
    385.                     }
    386.                 }
    387.                 else
    388.                 { //If it has not been bought (or is consumable)
    389.                     if (currentShownItemID < itemCosts.Length)
    390.                     {
    391.                         if (money >= itemCosts[currentShownItemID])
    392.                         { //If you have enough money to buy.
    393.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "BUY"; }
    394.                             if (itemCostDisplay != null) { itemCostDisplay.text = "Cost: " + RefinedMonetaryValue(itemCosts[currentShownItemID]); }
    395.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[2]; }
    396.                         }
    397.                         else
    398.                         { //If you are too poor to buy
    399.                             if (itemStatusDisplay != null) { itemStatusDisplay.text = "LOCKED"; }
    400.                             if (itemCostDisplay != null) { itemCostDisplay.text = "Cost: " + RefinedMonetaryValue(itemCosts[currentShownItemID]); }
    401.                             if (buyButtonImage != null) { buyButtonImage.color = statusColors[3]; }
    402.                         }
    403.                     }
    404.                 }
    405.             }
    406.         }
    407.     }
    408.  
    409.     int GetEquipmentState(int itemID)
    410.     {    //Gets if the displayed item is equipped.
    411.         int state = 0;     //A bool value
    412.         switch (itemEquipmentValues[itemID])
    413.         {  //Tests the value of itemEquipmentValues[itemID]
    414.             case 0: state = System.Convert.ToInt16(equippedHelmet == itemID); break;  //If the value of itemEquipmentValues[itemID] is 0, sets "state" to the numerical result of "true" or "false" depending in the comparison of equippedHelmet equaling itemID.
    415.             case 1: state = System.Convert.ToInt16(equippedWeapon == itemID); break;  //If the value is 1, sets "state" to the result of comparing if equippedWeapon equals itemID.
    416.             case 2: state = numberOfTribalDiscs; break;                       //If the value is 2, we get how many we have because we know its a consumable.
    417.         }
    418.         return state;
    419.     }
    420.  
    421.     void EquipItem(int itemID)
    422.     {    //Selects an Item
    423.         switch (itemEquipmentValues[itemID])
    424.         {  //Tests the value of itemEquipmentValues[itemID]
    425.             case 0: equippedHelmet = itemID; break;  //If the value of itemEquipmentValues[itemID] is 0, it equips to the Helmet Values
    426.             case 1: equippedWeapon = itemID; break;  //If the value is 1, It equips to the Weapons
    427.             case 2: break;                       //If the value is 2, nothing happens because its a consumable
    428.         }
    429.     }
    430.  
    431.     void Purchase(int itemID)
    432.     {     //Purchases the Item.
    433.         if (itemID < itemEquipmentValues.Length && itemID < itemCosts.Length && itemID < itemConsumableness.Length && itemID < shopItemsBought.Length)
    434.         {
    435.             switch (itemEquipmentValues[itemID])
    436.             { //Tests the value of itemEquipmentValues[itemID]
    437.                 case 0: equippedHelmet = itemID; break; //If the value of itemEquipmentValues[itemID] is 0, it sets equippedHelmet to itemID
    438.                 case 1: equippedWeapon = itemID; break; //If the value is 1, it sets equippedWeapon to itemID
    439.                 case 2: numberOfTribalDiscs++; break;   //If the value is 2, it adds 1 to our count of Tribal discs.
    440.             }
    441.             UpdateItemStatus();
    442.             money -= itemCosts[itemID];
    443.             UpdateMoney();
    444.             EquipItem(itemID);
    445.             if (!itemConsumableness[itemID]) { shopItemsBought[itemID] = true; }
    446.         }
    447.         else
    448.         {
    449.             Debug.LogError("Item Cannot be Purchased! Check Array Lenghts");
    450.         }
    451.     }
    452.  
    453.     string RefinedMonetaryValue(float monetaryValue)
    454.     {
    455.         string result = monetaryValue.ToString();
    456.         if (currencySymbolIsPrefix)
    457.         {
    458.             result = currencySymbol + monetaryValue.ToString();
    459.         }
    460.         else
    461.         {
    462.             result = monetaryValue.ToString() + currencySymbol;
    463.         }
    464.  
    465.         return result;
    466.     }
    467.  
    468.     void UpdateMoney()
    469.     {
    470.         if (moneyDisplayText != null) { moneyDisplayText.text = moneyDisplayIntroductoryText + RefinedMonetaryValue(money); }
    471.     }
    472.  
    473.     void OnBuyButtonClick()
    474.     {
    475.         if (currentShownItemID < itemCosts.Length && currentShownItemID < shopItemsBought.Length) {
    476.             if (money >= itemCosts[currentShownItemID] && !shopItemsBought[currentShownItemID]) { Purchase(currentShownItemID); }
    477.             if (shopItemsBought[currentShownItemID]) { EquipItem(currentShownItemID); }
    478.         }
    479.     }
    480.  
    481.     void OnNextPage()
    482.     {
    483.         currentShownItemID++;
    484.         if (currentShownItemID >= itemNames.Length) { currentShownItemID = 0; }
    485.         ShowItem(currentShownItemID);
    486.     }
    487.  
    488.     void OnPreviousPage()
    489.     {
    490.         currentShownItemID--;
    491.         if (currentShownItemID < 0) { currentShownItemID = itemNames.Length - 1; }
    492.         if (currentShownItemID < 0) { currentShownItemID = 0; Debug.LogError("No Items Defined!"); }
    493.         ShowItem(currentShownItemID);
    494.     }
    495. }
    The only thing that bothers me is that you have to manually edit parts of the script to fit your needs so its not completely straightaway. If the comments are not explanatory enough, I will explain it in this post with images.

    You can change the money from anywhere in any scene by just writing:
    Code (CSharp):
    1. ShopScript.money += amount;
    Which is very useful.
     
    Last edited: May 2, 2018
  26. WaqMan

    WaqMan

    Joined:
    Dec 13, 2018
    Posts:
    2
    Hi mate this looks awesome and a lot of hard work, were you able to make a video on it though? I'm having difficulty for this part of my project which is the final bit. If you have a video tutorial on it that would be fantastic!
     
  27. ArshidaGames

    ArshidaGames

    Joined:
    Feb 9, 2019
    Posts:
    93
    Hello , could you please do a video tutorial about your new script?
     
  28. MTalhaAli

    MTalhaAli

    Joined:
    May 29, 2018
    Posts:
    2
    can u give me shop
    i mean i need the how to change player prefab by buttons on click()

    can u give me your scripts?
    i need t change my player y changing values of variables in scipts (variables are attached to refabs)