c# - 我在 Unity 中的第一个 C# 游戏(介绍 playerprefs)
问题描述
在我的游戏中,有一个利润计数,它由我的货币脚本 ex 中的 addMoney 变量控制。利润数 = addMoney。
当我添加关于我的 addMoney 变量的播放器首选项时,它默认的 ProfitCount 为 0,而实际上它应该是 1。这是我的第一个游戏,所以它很容易成为我误解或忽视的小事。
钱数
public class moneyCount : MonoBehaviour
{
float timeTillAdd = 1;
public int addMoney = 1;
public int money;
public Text txt;
// Start is called before the first frame update
void Start()
{
money = PlayerPrefs.GetInt("Money");
addMoney = PlayerPrefs.GetInt("addmoney");
}
// Update is called once per frame
void Update()
{
PlayerPrefs.SetInt("addmoney", addMoney);
if (Time.time >= timeTillAdd)
{
money += addMoney;
timeTillAdd++;
}
txt.text = money.ToString();
PlayerPrefs.SetInt("Money", money);
}
}
利润计算
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class profitCount : MonoBehaviour
{
public int profitAmount;
public GameObject moneyManagerObj;
moneyCount mc;
public Text txt;
// Start is called before the first frame update
void Start()
{
mc = moneyManagerObj.GetComponent<moneyCount>();
// profitAmount = PlayerPrefs.GetInt("profitamount");
}
// Update is called once per frame
void Update()
{
profitAmount = mc.addMoney;
txt.text = profitAmount.ToString();
// PlayerPrefs.SetInt("profitamount", profitAmount);
}
}
商店管理员
public class ShopManager : MonoBehaviour
{
public int item1_cost = 50;
public int item1_upgrade = 5;
public int item1_tier = 1;
public int item2_cost = 50;
public int item2_upgrade = 5;
public GameObject moneyManagerObj;
moneyCount mc;
public Text txt;
public Text item1;
public Text item1_text;
// Start is called before the first frame update
void Start()
{
mc = moneyManagerObj.GetComponent<moneyCount>();
item1_cost = PlayerPrefs.GetInt("Item1_cost");
//item1_upgrade = PlayerPrefs.GetInt("Item1_upgrade");
item1_tier = PlayerPrefs.GetInt("Item1_tier");
}
// Update is called once per frame
void Update()
{
item1.text = item1_tier.ToString();
PlayerPrefs.SetInt("Item1_cost", item1_cost);
// PlayerPrefs.SetInt("Item1_upgrade", item1_upgrade);
PlayerPrefs.SetInt("Item1_tier", item1_tier);
if (item1_tier > 0)
{
item1_text.text = ("Upgrade");
}
}
public void on_click()
{
{
if (mc.money >= item1_cost)
{
mc.money -= item1_cost;
mc.addMoney += item1_upgrade;
item1_tier += 1;
item1.text = item1_tier.ToString();
item1_cost += 50 * item1_tier;
}
}
}
}
解决方案
两件事情:
不要
PlayerPrefs
用来存储存档数据。这不是为了那个。它用于保存播放器首选项,例如音量、全屏模式或输入类型。使用的文件PlayerPrefs
是纯文本,不支持复杂的数据类型。如果不存在保存数据,则读出的值为零(至少来自 PlayerPrefs)。你需要考虑到这一点,而目前你不是。当您使用不同的保存方法时,您会遇到其他错误,例如空指针或未找到文件。您必须确定是否存在保存,并且仅当存在时,您才应该从中读取。
推荐阅读
- elasticsearch - Elasticsearch Cluster can't see each other
- python - 在 Python 中使用 wav 文件录制音频和语音到文本的转换
- spring-boot - Spring Cloud 配置身份验证问题
- python-3.x - LabelEncoder: ValueError- y 包含以前看不见的标签:
- javascript - 在循环内使用时刻时的奇怪结果
- javascript - Angular:在 ngFor 内绑定 ngIf
- sql-server - SQL Server 在没有权限的情况下将页面锁定在内存中
- javascript - 如何在不更改键顺序的情况下根据属性值拆分数组?
- typescript - 打字稿构造函数中的“new()=>”
- matlab - 如何在绘图中的标签值及其表示值之间添加空格?