- Home /
How to add a coin sytem to my game?
Hello everyone, I'm trying to make a coin system to my game but I'm facing these two problems: 1) The text doesn't display anything in the game screen, but i can see it when i'm in build mode 2) It doesn't show anything until i pickup a coin, and when i do, it only says 1 no matter how many coins i pick up. My coins are all tagged with cointag I've double checked, and they do get destroyed, but it doesn't make the int coin go up. I also added using UnityEngine.UI. I'd appreciate if someone could answer my question. Thanks
public class SnowmanController : MonoBehaviour { // Update is called once per frame public int coin; public Text coinText;
void Update ()
{
coin = 0;
if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += new Vector3 (0.1f, 0, 0);
} else if (Input.GetKey (KeyCode.LeftArrow)) {
transform.position -= new Vector3 (0.1f, 0, 0);
} if (Input.GetKey (KeyCode.UpArrow) | Input.GetKey (KeyCode.Space)) {
transform.position += new Vector3 (0, 0.1f, 0);
} else if (Input.GetKey (KeyCode.DownArrow)) {
transform.position -= new Vector3 (0, 0.1f, 0);
} else if (Input.GetKey (KeyCode.R)) {
SceneManager.LoadScene ("Level1");
}
}
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "cointag") {
Destroy (other.gameObject);
coin = coin + 1;
coinText.text = "Coin: " + coin.ToString ();
} else if (other.gameObject.tag == "treetag") {
SceneManager.LoadScene ("Level 2");
}
}
}
You are setting coin to 0 in every frame in the Update function.
Answer by pluetoe · Dec 02, 2017 at 04:29 AM
Move the "Coin" variable out of the "update function", because it resets the coin value to one every frame.
e.g
// initialize the value to zero here
coin = 0;
void Update () {}...
This should fix your problem :)