Unity3D仿星露谷物语开发57之保存库存信息到文件
1、目标
保存下面库存栏中信息到文件中。
2、修改SceneSave.cs脚本
添加2行代码:
3、修改InventoryManager对象
添加Generate GUID组件。
4、修改InventoryManager.cs脚本
添加继承自ISaveable
添加属性信息:
private string _iSaveableUniqueID;public string ISaveableUniqueID { get { return _iSaveableUniqueID; } set { _iSaveableUniqueID = value; } }private GameObjectSave _gameObjectSave;public GameObjectSave GameObjectSave { get { return _gameObjectSave; } set { _gameObjectSave = value; } }private UIInventoryBar inventoryBar;
在Awake()方法中添加2行代码:
添加如下几个方法:
private void OnDisable(){ISaveableDeregister();}private void OnEnable(){ISaveableRegister();}private void Start()
{inventoryBar = FindObjectOfType<UIInventoryBar>();
}public void ISaveableRegister(){SaveLoadManager.Instance.iSaveableObjectList.Add(this);}public void ISaveableDeregister(){SaveLoadManager.Instance.iSaveableObjectList.Remove(this);}public GameObjectSave ISaveableSave(){// Create new scene saveSceneSave sceneSave = new SceneSave();// Remove any existing scene save for persistent scene for this gameobjectGameObjectSave.sceneData.Remove(Settings.PersistentScene);// Add inventory lists array to persistent scene savesceneSave.listInvItemArray = inventoryLists;// Add inventory list capacity array to persistent scene savesceneSave.intArrayDictionary = new Dictionary<string, int[]>();sceneSave.intArrayDictionary.Add("inventoryListCapacityArray", inventoryListCapacityIntArray);// Add scene save for gameobjectGameObjectSave.sceneData.Add(Settings.PersistentScene, sceneSave);return GameObjectSave;}public void ISaveableLoad(GameSave gameSave){if(gameSave.gameObjectData.TryGetValue(ISaveableUniqueID, out GameObjectSave gameObjectSave)){GameObjectSave = gameObjectSave;// Need to find inventory lists - start by trying to locate saveScene for game objectif(gameObjectSave.sceneData.TryGetValue(Settings.PersistentScene, out SceneSave sceneSave)){// list inv items array exists for persistent sceneif(sceneSave.listInvItemArray != null){inventoryLists = sceneSave.listInvItemArray;// Send events that inventory has been updatedfor(int i = 0; i < (int)InventoryLocation.count; i++){EventHandler.CallInventoryUpdatedEvent((InventoryLocation)i, inventoryLists[i]);}// Clear any items player was carryingPlayer.Instance.ClearCarriedItem();// Clear any highlights on inventory barinventoryBar.ClearHighlightOnInventorySlots();}// int array dictionary exists for sceneif(sceneSave.intArrayDictionary != null && sceneSave.intArrayDictionary.TryGetValue("inventoryListCapacityArray", out int[] inventoryCapacityArray)){inventoryListCapacityIntArray = inventoryCapacityArray;}}}}public void ISaveableStoreScene(string sceneName){// Nothing required here since the inventory manager is on a persistent scene;}public void ISaveableRestoreScene(string sceneName){// Nothing required here since the inventory manager is on a persistent scene;}
5、运行游戏
角色收集的item放到库存栏中,save game后退出游戏,重新进入游戏后load game,库存栏中的信息保持不变。