为了账号安全,请及时绑定邮箱和手机立即绑定

我在Unity中的第一款C#游戏(介绍playerprefs)

我在Unity中的第一款C#游戏(介绍playerprefs)

C#
慕尼黑8549860 2022-08-20 16:58:22
在我的游戏中,有一个利润计数由我的货币脚本中的addMoney变量控制,例如利润计数= addMoney。当我添加关于我的addMoney变量的玩家pref时,它将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);    }}
查看完整描述

2 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

两件事:

  1. 不要用于存储保存数据。它不是为此而生的。它旨在保存播放器首选项,例如音量,全屏模式或输入类型。使用的文件是纯文本,不支持复杂的数据类型。PlayerPrefsPlayerPrefs

  2. 如果不存在保存数据,则读出的值为零(至少从 PlayerPrefs 中读取)。您需要对此负责,而目前您不是。当您改用其他保存方法时,您会收到其他错误,例如空指针或未找到文件。您必须确定保存是否存在,并且仅当存在保存时,才应从中读取。


查看完整回答
反对 回复 2022-08-20
?
蛊毒传说

TA贡献1895条经验 获得超3个赞

好的,所以你在初始化期间分配了默认值,即addMoneypublic int addMoney = 1;

但是,在开始时,您再次为它分配了一个尚未保存的值。addMoney = PlayerPrefs.GetInt("addmoney");

如果要创建记录,请按如下方式操作PlayerPrefs.SetInt("addmoney",addmoney);


查看完整回答
反对 回复 2022-08-20
  • 2 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信