Unity2D: Fixing Coin System
The way my coin system works is simple.
The player starts off with 10 fruit automatically
The enemies will then spawn in and steal a random amount of fruit from the player, the amount of fruit the enemy will steal varies from a random integer to the amount the player previously had.
The player can get more fruit by stabbing the enemies, the amount of fruit the player will get varies from a random integer to random integer.
However if the enemy takes a random amount of fruit from the player and then the player then stabs the enemy, the player will get back however much fruit the enemy took from them, plus the an extra bonus of fruit from the enemy (please look at point 3, if needed).
My problem:
This only happens occasionally, but sometimes the coin system will refuse to work especially during the beginning of the game or if the player has a large amount of fruit, i.e. 300 fruits. For example, if the player has about 300 fruits and the enemy takes about 200 fruits from the player (meaning the player will have 100 fruits remanding), then if the player stabs the enemy, the player will only receive about (for example) 25 fruits back instead of the initial 200 + the bonus(for example) 25. As mentioned before, this only happen occasionally - sometimes more than usual however I'd still like to make sure that it works accurately and smoothly. I have tried debugging it, but I am still stuck with why it is not working properly. Can anyone help me fix my codes or give me a better solution as to how I can make a better coin system. Thank you!
Enemy Theft script:
public static int scoreValue;
void Start () {
scoreValue = 0;
}
void Update () {
Debug.Log ("ScoreValue: " + scoreValue);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Farm") {
collidedwithFarm = true;
scoreValue = Random.Range (1, GameController.Fruit);
Debug.Log ("Enemy takes: " + scoreValue);
GameController.Fruit-= scoreValue;
//Wallet += scoreValue;
if (GameController.Fruit<= 0) {
GameController.Fruit = 0;
}
}
}
Enemy's script:
public int randomValue;
public int wallet;
public bool collidedwithFarm = false;
// Use this for initialization
void Start () {
wallet = 0;
collidedwithFarm = false;
randomValue = Random.Range (1, 101);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "playerKnife") {
if (collidedwithFarm == false) {
text.text = " " + randomValue;
Debug.Log ("NOT COLLISION");
GameController.Fruit+= randomValue;
}
else if (collidedwithFarm == true) {
Debug.Log ("COLLISION");
GameController.Fruit+= EnemyTheft.scoreValue+ randomValue;
Debug.Log("Player gets back: " + EnemyTheft.scoreValue);
wallet += EnemyTheft.scoreValue + randomValue;
text.text = " " + wallet;
Debug.Log ("In total: " + wallet);
}
}
}
Coin Script:
public Text FruitText;
public static int Fruit = 10;
void Start()
{
SetFruitText ();
Fruit = 10;
}
void SetFruitText ()
{
FruitText.text = "Fruits: " + Fruit.ToString();
}