Need some guidance..

Hello everyone,

Ive been learning to code for the past 6 months by creating a small game and slowly adding simple features to it. I’m trying to find a good tutorial that explains how to store collected coins and use them in a shop setting. I currently have a coin collection system that updates while playing but doesn’t save. I have a float for gold in my player controller that updates in my UI as I collect. This is what I currently have set up, I was thinking of using playerprefs ( seems to be the less complicated one to store data) but no idea how to go about it. My Start function starts my gold float at zero, and update method has this updated to my text: GoldText.text = Gold + “”;

Any guidance on where to go or any good videos I would appreciate. I cant find any good tutorials that tie in the collecting and saving coins with using it in a shop to buy items,skins etc.

public void AddGold()
    {
        Gold += 1f;
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Gold")
        {
            AddGold();
            PlayPickUpSound();
            Destroy(collision.gameObject);
        }
    }

Thank you for your time and help.

Is there ever an instance where the player would have a fraction of a gold? Such as the player having 1.2273 gold? If not, then you should use one of the integer types instead of a float.

As far as saving, there’s already a lot of threads on using PlayerPrefs and using JSON for save systems. On PlayerPrefs, there’s a comment in the below thread I wrote recently which explains how PlayerPrefs works. Let me know if it still doesn’t make sense.

Alternatively you could create your own text or even binary save format, but that’s less beginner friendly.

1 Like

As you correctly assumed, PlayerPrefs would be one of the quickest ways to go about storing small chunks of information like that. When in doubt about how to approach something, take a look at the documentation, as it comes with explanations and examples: Unity - Scripting API: PlayerPrefs

The whole thing works by storing values of a specific type using a key (to remember them by). So when you know what value you want to store, you can just take a look at the specific method call to gain more information. In your case your gold value seems to be a float. As @Joe-Censored already stated, unless there are cases where you actually have fractions of gold, you may want to change that to integer. Anyways, to store a float, you’d use SetFloat:

To then later load it, you’d use GetFloat accordingly.

The examples provided there should be enough to figure out how it works, but here you go anyways:

// OnApplicationQuit or whenever you want to save the data:
PlayerPrefs.SetFloat("Gold", Gold);

// In Start() or anywhere else when you want to load the value:
Gold = PlayerPrefs.GetFloat("Gold", 0f); // the second value is the default if it does not find an entry named "Gold"
2 Likes

It’s worth nothing that player preferences are for exactly that - player preferences. You should keep in mind that if you store data such as how many coins a player has, they could easily go in and change the value.

If it’s a single player game and/or you don’t care about this - fine. However, you might want to consider something a little more secure.

You could use a generic so template to store the gold amount (this could also be used for anything that requires an integer… hence the generic name)

GenericIntSO.cs

using UnityEngine;

[CreateAssetMenu(fileName = "Data", menuName = "SO/Generc/Int", order = 1)]
public class GenericIntSO : ScriptableObject
{
    public int value;
}

GoldData.cs

[Serializable]
public class GoldData
{
    public int gold;
}

SomeScript.cs

public GenericIntSO gold;

GoldData goldData = new GoldData();

goldData.gold = gold.value;

// serialize
string json = JsonUtility.ToJson(goldData);

Debug.Log(goldData.value);

// deserialize
goldData = JsonUtility.FromJson<GoldData>(json);

gold.value = goldData.gold;

You could use a static class so you can add/remove coins from any other script just by calling a method and passing in some parameters.

SomeStaticClass.cs

public static class SomeStaticClass
{
    public static ModifyCoinBalance(bool add, int amount)
    {
        if (add)
        {
            // add coins to balance
        }
        else
        {
            // remove coins to balance
        }
    }

    public static int ReturnCoinBalance()
    {
        return int getTheCoinBalanceHere;
    }
}

Then I guess for the shop you could have something like:

public class ShopManager : MonoBehaviour
{
    public Button item_01;

    void Start()
    {
        item_01.onClick.AddListener(delegate {PurchaseItem(1, 1000);});
    }

    void PurchaseItem(int itemID, int itemPrice)
    {
        // check player coin balance
        // if they have enough, let them purchase the item
    }
}
1 Like

Thank you all for the great answers! This will help me a ton in learning how to add more features and continue my learning.