- Home /
Coins store problem !!!
Can anyone please help me with this ? My coins are deleting after i restart the game or I die ... How can I save them ?
Here is my code:
using UnityEngine;
using System.Collections;
public class Coins : MonoBehaviour {
private uint coins = 0;
public Texture2D coinIconTexture;
// Use this for initialization
void Start () {
}
void CollectCoin(Collider2D coinCollider)
{
coins++;
Destroy(coinCollider.gameObject);
}
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.CompareTag("Coins"))
CollectCoin(collider);
}
void DisplayCoinsCount()
{
Rect coinIconRect = new Rect(10, 10, 32, 32);
GUI.DrawTexture(coinIconRect, coinIconTexture);
GUIStyle style = new GUIStyle();
style.fontSize = 30;
style.fontStyle = FontStyle.Bold;
style.normal.textColor = Color.yellow;
Rect labelRect = new Rect(coinIconRect.xMax, coinIconRect.y, 60, 32);
GUI.Label(labelRect, coins.ToString(), style);
}
void OnGUI()
{
DisplayCoinsCount();
}
// Update is called once per frame
void Update () {
}
}
PlyaerPref is best option for it, you can use it like Jeric instruction. another way you can store it some where in data file like text, sqlLite, but it's time consumeing process, right now PlaerPref is the better option.
I must say, "Coins store problem !!!" is the most descriptive and accurate title for a question I have ever seen. (Obvious sarcasm is obvious)
Please post proper questions, with a proper question, a proper description and a proper title. If you don't know what is expected here, watch the tutorial video and read the FAQ.
read http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
PlayerPrefs.SetInt("Coins",coins);
If you want to display with the text:
public GUIText CoinText;
void Start()
{
CoinText.text="Coins" + PlayerPrefs.GetInt("Coins");
}
I'm not good at C# but I'm pretty sure thats how you do it
Answer by Jeric-Miana · Sep 08, 2014 at 05:26 AM
You can save it by using PlayerPrefs.
For reference see here -> http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
public GUIText showCoins;
void OnTriggerEnter2D(other : Collider2D)
{
if(other.tag=="Coins")
{
coins++;
PlayerPrefs.SetInt("Coins",coins);
}
}
void Update()
{
showCoins.text="Coins" + PlayerPrefs.GetInt("Coins");
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613162538im_/https://answers.unity.com/themes/thub/images/avi.jpg)