В начале все работало, клики, метод сохранения очков и т. д.
Потом Я хотел добавить магазин, который будет улучшать щелчок мышью пользователя (по сути, за каждый щелчок добавляется больше очков). Сейчас работает и не работает. При отладке, после покупки обновления пишет, что сохранен правильный балл, но когда закрываю магазин или нажимаю еще раз, сохраняется балл, который был до покупки обновления.Есть исправления?
StrawberryClicker.cs
Код: Выделить всё
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class StrawberryClicker : MonoBehaviour
{
public Button clickButton;
public Text clickCountText;
public Text dropTimeText;
private int clickCount = 0;
private int mousePower = 1;
private float clickTime = 0;
private float dropTimer = 0;
private float dropInterval = 3 * 3600; // 3 hours in seconds
private float idleDropInterval = 18 * 3600; // 18 hours in seconds
private bool isClicking = false;
private float lastClickTime = 0;
private string userId;
void Start()
{
clickButton.onClick.AddListener(OnClick);
userId = LocalStorageManager.GetUserId();
// Load the score when the game starts
LoadScore();
mousePower = PlayerPrefs.GetInt("MousePower", 1);
// Automatically save score every 5 seconds
InvokeRepeating("SaveScore", 5f, 5f);
}
public void StartSavingScore()
{
InvokeRepeating("SaveScore", 5f, 5f);
}
public void StopSavingScore()
{
CancelInvoke("SaveScore");
}
void Update()
{
clickTime += Time.deltaTime;
if (isClicking)
{
lastClickTime = clickTime;
if (clickTime - dropTimer >= dropInterval)
{
}
}
else if (clickTime - lastClickTime >= 60)
{
if (clickTime - dropTimer >= idleDropInterval)
{
}
}
dropTimeText.text = $"Next Drop In: {(dropInterval - (clickTime - dropTimer)) / 3600:F2} hours";
}
// Add this variable
public int ClickCount { get { return clickCount; } }
// Modify OnClick method
void OnClick()
{
clickCount += mousePower;
isClicking = true;
clickCountText.text = $"Clicks: {clickCount}";
// Add this line to update click count in ShopManager
FindObjectOfType().UpdateClickCount(clickCount);
}
public void SaveScore()
{
LocalStorageManager.SaveScore(clickCount);
}
void LoadScore()
{
clickCount = LocalStorageManager.LoadScore();
clickCountText.text = $"Clicks: {clickCount}";
}
}
Код: Выделить всё
using UnityEngine;
using UnityEngine.UI;
public class ShopManager : MonoBehaviour
{
public GameObject shopPanel;
public Button shopButton;
public Button closeButton;
public Button buyMousePowerButton;
public Text clickCountText;
public Text mousePowerText;
private int clickCount;
private int mousePower = 1;
private int mousePowerCost = 50;
private int mousePowerBought = 0;
// Add this variable
private StrawberryClicker strawberryClicker;
void Start()
{
// Add these lines to update the click count when the shop is opened
strawberryClicker = FindObjectOfType();
clickCount = strawberryClicker.ClickCount;
UpdateUI();
mousePower = PlayerPrefs.GetInt("MousePower", 1);
mousePowerBought = PlayerPrefs.GetInt("MousePowerBought", 0);
shopPanel.SetActive(false);
shopButton.onClick.AddListener(OpenShop);
closeButton.onClick.AddListener(CloseShop);
buyMousePowerButton.onClick.AddListener(BuyMousePower);
}
// Add this method to update click count when it changes in StrawberryClicker
public void UpdateClickCount(int newClickCount)
{
clickCount = newClickCount;
UpdateUI();
}
void UpdateUI()
{
clickCountText.text = $"Clicks: {clickCount}";
mousePowerText.text = $"Mouse Power: {mousePower} (Bought: {mousePowerBought})";
}
public void OpenShop()
{
shopPanel.SetActive(true);
// Stop saving the score when the shop is opened
FindObjectOfType().StopSavingScore();
}
public void CloseShop()
{
// Save the score before closing the shop
FindObjectOfType().SaveScore();
shopPanel.SetActive(false);
// Resume saving the score when the shop is closed
FindObjectOfType().StartSavingScore();
}
public void BuyMousePower()
{
Debug.Log("BuyMousePower() called");
Debug.Log($"clickCount: {clickCount}, mousePowerCost: {mousePowerCost}");
if (clickCount >= mousePowerCost)
{
Debug.Log("Purchase successful");
clickCount -= mousePowerCost;
mousePower++;
mousePowerBought++;
// Save the updated score immediately after the purchase
LocalStorageManager.SaveScore(clickCount);
// Update the UI with the new score
UpdateUI();
// Save the mouse power and mouse power bought values
PlayerPrefs.SetInt("MousePower", mousePower);
PlayerPrefs.SetInt("MousePowerBought", mousePowerBought);
}
else
{
Debug.Log("Insufficient clicks to purchase Mouse Power");
}
}
}
Код: Выделить всё
using UnityEngine;
using System;
using System.Security.Cryptography;
using System.Text;
public class LocalStorageManager : MonoBehaviour
{
private static string userIdKey = "user_id";
private static string scoreKey = "score";
// Define your secret key here
private static readonly string secretKey = "s3cr3tK3y@123"; // Replace this with a securely generated key
public static string GetUserId()
{
if (!PlayerPrefs.HasKey(userIdKey))
{
string newUserId = GenerateUserId();
PlayerPrefs.SetString(userIdKey, newUserId);
PlayerPrefs.Save();
return newUserId;
}
else
{
return PlayerPrefs.GetString(userIdKey);
}
}
public static void SaveScore(int score)
{
string encryptedScore = Encrypt(score.ToString());
PlayerPrefs.SetString(scoreKey, encryptedScore);
PlayerPrefs.Save();
Debug.Log($"Score saved: {score}");
}
public static int LoadScore()
{
if (PlayerPrefs.HasKey(scoreKey))
{
string encryptedScore = PlayerPrefs.GetString(scoreKey);
string decryptedScore = Decrypt(encryptedScore);
if (int.TryParse(decryptedScore, out int score))
{
Debug.Log($"Score loaded: {score}");
return score;
}
}
Debug.Log("No score found, returning default score 0");
return 0; // Default score if not found
}
private static string GenerateUserId()
{
return Guid.NewGuid().ToString();
}
private static string Encrypt(string plainText)
{
byte[] data = Encoding.UTF8.GetBytes(plainText);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] keys = md5.ComputeHash(Encoding.UTF8.GetBytes(secretKey));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider()
{
Key = keys,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
})
{
ICryptoTransform transform = tripDes.CreateEncryptor();
byte[] results = transform.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(results, 0, results.Length);
}
}
}
private static string Decrypt(string cipherText)
{
byte[] data = Convert.FromBase64String(cipherText);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] keys = md5.ComputeHash(Encoding.UTF8.GetBytes(secretKey));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider()
{
Key = keys,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
})
{
ICryptoTransform transform = tripDes.CreateDecryptor();
byte[] results = transform.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(results);
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... rp-project