'Player absence time in Unity
Good day, I am making a 2d android game on Unity 2020.3.30. I am accruing money while the player is not in the game. The problem is, if you click 107 coins and exit the game for 5 seconds, then the money will not be 112 (as it should be (107 coins + 5 coins)) but 105, that is to 100 coins, for some reason, the number of seconds is added, and not to 107. How to fix it?
Script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
[SerializeField] int money;
public int total_money;
public Text moneyText;
private void Start()
{
money = PlayerPrefs.GetInt("money");
total_money = PlayerPrefs.GetInt("total_money");
bool isFirst = PlayerPrefs.GetInt("isFirst") == 1 ? true : false;
if (isFirst)
{
StartCoroutine(IdleFarm());
}
OfflineTime();
}
public void ButtonClick()
{
money++;
total_money++;
PlayerPrefs.SetInt("money", money);
PlayerPrefs.SetInt("total_money", total_money);
}
IEnumerator IdleFarm()
{
yield return new WaitForSeconds(1);
money++;
Debug.Log(money);
PlayerPrefs.SetInt("money", money);
StartCoroutine(IdleFarm());
}
private void OfflineTime()
{
TimeSpan ts;
if (PlayerPrefs.HasKey("LastSession"))
{
ts = DateTime.Now - DateTime.Parse(PlayerPrefs.GetString("LastSession"));
Debug.Log(string.Format("You were gone for {0} days, {1} hours, {2} minutes, {3} seconds", ts.Days, ts.Hours, ts.Minutes, ts.Seconds));
money += (int)ts.TotalSeconds;
}
}
#if UNITY_ANDROID && !UNITY_EDITOR
private void OnApplicationPause(bool pause)
{
if (pause)
{
PlayerPrefs.SetString("LastSession", DateTime.Now.ToString());
}
}
#else
private void OnApplicationQuit()
{
PlayerPrefs.SetString("LastSession", DateTime.Now.ToString());
}
#endif
public void ToAchievements()
{
PlayerPrefs.SetString("LastSession", DateTime.Now.ToString());
SceneManager.LoadScene(1);
}
// Update is called once per frame
void Update()
{
moneyText.text = money.ToString();
}
}
Solution 1:[1]
You can try some methods with collision detection, which can be applied to collect gold coins. Create a gold coin model and paste the above code in its C# code to collect gold coins,Thank you, hope it helps you
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")//If the colliding object is the player
{
money++;//money plus one
Destroy(this.gameObject);//Destroy coins
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
