I’m having issues with some of my code:
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class TimeController : MonoBehaviour {
[HideInInspector]
public float money;
public float earningsMultiplier = 1;
public float timeBetweenSaves = 10;
public Text t;
TimeSpan timeDifference;
private void Start()
{
timeDifference = DateTime.UtcNow - DateTime.Parse(PlayerPrefs.GetString("lastSavedTimeAndDate"));
PlayerPrefs.SetString("totalMoney", (getCurrentMoney() + timeDifference.TotalSeconds * earningsMultiplier).ToString());
InvokeRepeating("SaveDataPeriodically",timeBetweenSaves, timeBetweenSaves);
money = getCurrentMoney();
}
private void Update()
{
money += Time.deltaTime * earningsMultiplier;
PlayerPrefs.SetString("totalMoney", money.ToString());
//Keep last saved time up to date (HA! Unintentional puns rule XD!)
PlayerPrefs.SetString("lastSavedTimeAndDate", DateTime.UtcNow.ToString());
t.text = "Current Credits: " + money.ToString();
}
IEnumerator SaveDataPeriodically() { PlayerPrefs.Save(); return null; }
public float getCurrentMoney() { return float.Parse(PlayerPrefs.GetString("totalMoney")); }
public void PurchaseItem(float cost) { money -= cost; }
public bool CanAfford(float unitCost) { if (money >= unitCost) { return true; } return false; }
}
The issue seems to be this line here:
money += Time.deltaTime * earningsMultiplier;
For some reason, it seems to be rounding Time.deltaTime * earningsMultiplier to zero if I set earningsMultiplier to something smaller than 1. Even 0.9 seems to bug out a bit. Does anyone know why it would be rounding this? Money is supposed to increment over time (This is code for something similar to a cookie clicker game where money increments over time), but at the moment due to this bug it stays where it is if the multiplier is small enough. I cannot continue my game until this bug is sorted. Any suggestions are welcome
Edit: It does not round Time.deltaTime * earningsMultiplier to zero. Instead, it just doesn’t add the tiny value of Time.deltaTime * earningsMultiplier to money for some reason. E.g. 300,000.7 + 0.00016 = 300,000.7 according to unity. You can see where the bug occurs. Yet, for example, 300,000.7 + 0.016 = 300,000.716