c# - 使用循环保存所有武器 ID 编号
问题描述
我没有编程背景,我正在玩 Unity Engine。所以我有一个项目经理。所有武器都有 ID 号,例如 23 代表斧头,9 代表手枪等...
我正在尝试制作一个保存加载系统。
public void save() {
var itemManager = gameObject.GetComponent<vItemManager>();
if (itemManager != null) {
foreach(var weapon1 in itemManager.items) {
// Shows all Weapon Id numbers that is equipped (in the console)
Debug.Log(weapon1.id);
/*
It just saves the id of the last weapon equipped other weapons ids are
missing....(the id of the last weapon was saved into registry i want to save all weapon ids into registry..)
Playerprefs: Stores and accesses player preferences between game
sessions.
SetInt: Sets the value of the preference identified by key.
*/
PlayerPrefs.SetInt ("nummer", weapon1.id);
}
}
}
解决方案
您必须使用唯一密钥进行保存。但是您对所有 id 使用相同的密钥:“nummer”。
int i = 0;
foreach(var weapon1 in itemManager.items) {
PlayerPrefs.SetInt ("nummer_" + i++, weapon1.id);
}
但是有一个问题:你将如何从 PlayerPrefs 中读取未知键?更好的方法是将您的武器清单序列化到文件中。
https://docs.unity3d.com/Manual/script-Serialization.html https://unity3d.com/ru/learn/tutorials/topics/scripting/serialization-and-game-data
或者您可以将所有 id 组合成字符串,将它们保存到 PlayerPrefs 并在读取时解析:
//save
String weaponsList;
foreach(var weapon1 in itemManager.items) {
weaponsList += weapon1.id + ',';
}
PlayerPrefs.SetString ("weapons",weaponsList);
//load
String weaponsList = PlayerPrefs.GetString("weapons", String.Empty);
var weaponsIds= weaponsList.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
foreach(var weaponId in weaponsIds) {
//...
}
推荐阅读
- python - 为什么 Altair 条形图中最左边的条不尊重选择画笔位置?
- pandas - 根据列值创建列 - 循环列
- elasticsearch - 如果/何时随时间变化,是否有一种快速且可扩展的方式让 Elasticsearch 在已定义/查询的结果上触发事件?
- r - 如何在数据框列中存储“米上标减 3”
- android - 如何忽略 Parent Layout 的背景
- java - PreferenceFragmentCompat 未显示 XML 中的所有首选项
- c# - 如何在c#中的每批请求中保持5秒的间隔
- shell - 通过应用程序安装执行命令时出现“grep:写入错误:管道损坏”
- node.js - 如何在 Puppeteer 的请求中通过 post 添加数据?
- visual-studio-code - 如何阻止 VScode 在我的源文件夹中创建 .vscode 文件夹