首页 > 解决方案 > 使用循环保存所有武器 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); 
            }
        }
}

标签: c#linqloopsunity3dforeach

解决方案


您必须使用唯一密钥进行保存。但是您对所有 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) {
   //...
}

推荐阅读