- Home /
I´ve got a problem with my Coin System. It always shows 1 Coin.
I´ve got a question to a Coin System I created. The shown value is 1 and keeps 1 although it should be 0 at the beginning and should get bigger on touching coins. My Scripts are:
Player:
using UnityEngine;
using System.Collections;
public class FigurBewegeDich : MonoBehaviour {
public float moveForce = 300f;
public float maxSpeed = 5f;
public static int Coins = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float direction = Input.GetAxis ("Mouse X");
if (direction != 0f) {
rigidbody2D.AddForce (
Vector2.right * direction * moveForce);
rigidbody2D.velocity = Vector2.ClampMagnitude (
rigidbody2D.velocity, maxSpeed);
}
float direction2 = Input.GetAxis ("Mouse Y");
if (direction2 != 0f) {
rigidbody2D.AddForce (
Vector2.up * direction2 * moveForce);
rigidbody2D.velocity = Vector2.ClampMagnitude (
rigidbody2D.velocity, maxSpeed);
}
}
}
GUIText:
using UnityEngine;
using System.Collections;
public class ShowCoins : MonoBehaviour {
public int Coins1 = 0;
public string Coins2="0";
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
Coins1 = PlayerPrefs.GetInt ("Coins");
Coins2 = Coins1.ToString();
guiText.text = Coins2;
}
}
Coins:
using UnityEngine;
using System.Collections;
public class CoinScript : MonoBehaviour {
public int Coins = 0;
public float PosY = 0;
// Use this for initialization
void Start () {
PosY = transform.position.y;
transform.position =
new Vector3(Mathf.Round (Random.value * 18 - 9),PosY,0);
}
// Update is called once per frame
void FixedUpdate () {
}
void OnTriggerEnter2D(Collider2D other){
if (other.name == "Figur") {
PlayerPrefs.SetInt("Coins",Coins+1);
Destroy (gameObject);
}
}
}
Answer by tanoshimi · Feb 22, 2015 at 07:01 PM
The value of "Coins" in CoinScript is 0 (line 4) and always remains so.
The value of PlayerPrefs ("Coins") is set to always be 1 greater than this (line 17 of CoinScript) and always remains so.
The value of the GuiText is set to always be the value in the PlayerPrefs (Guitext line 11).
So, it'll always display 1...
Answer by Jessespike · Feb 22, 2015 at 07:09 PM
void FixedUpdate () {
//Coins1 = PlayerPrefs.GetInt ("Coins");
//Coins2 = Coins1.ToString();
//guiText.text = Coins2;
guiText.text = Player.Coins.ToString();
}
void OnTriggerEnter2D(Collider2D other){
if (other.name == "Figur") {
//PlayerPrefs.SetInt("Coins",Coins+1);
Player.Coins++;
Destroy (gameObject);
}
There seems to be some confusion with PlayerPrefs and your Player class that exposes a public static.
I cant change a static variable from another Script this way. It doesnt work in your way.