Hello! I’m trying to make sure that inventory data, or rather items in it, are saved from session to session. It doesn’t work. What am I doing wrong? I noticed that my json and filePath files are not being written. When debugging, it outputs {} to the console
Here is a class with data
[System.Serializable]
public class ItemData
{
public string Name;
public int Quantity;
public int Defence;
public ItemData(string name, int quantity, int defence)
{
this.Name = name;
this.Quantity = quantity;
this.Defence = defence;
}
}
Here is the code with the items, they are then added to the inventory.
public class Items : MonoBehaviour
{
public int[] DefenceItems = new int[] { 5, 10, 15, 20, 25 };
public bool[] HasItems = new bool[] { false, false, false, false, false };
public string[] NameItems = new string[] { "Bandit Pants", "Bulletproof cloak", "Bulletproof cloak Elbow", "Bulletproof cloak wrist", "Military Helmet" };
public int[] Quantity = new int[] { 0, 0, 0, 0, 0 };
public GameObject Character;
public Sprite[] Sprites;
public ItemData ItemDataScript;
[SerializeField] private List<ItemData> items = new List<ItemData>();
private int _currentItem;
private int _currentDefence;
private void Start()
{
LoadItems();
}
public void Equip(int index)
{
if (HasItems[index])
{
_currentItem = index;
_currentDefence = DefenceItems[_currentItem];
Character.GetComponent<SpriteRenderer>().sprite = Sprites[_currentItem];
}
}
public void AddItem(int index)
{
HasItems[index] = true;
if (HasItems[index])
{
Quantity[index]++;
}
SaveItems();//
}
Save
public void SaveItems()
{
//List<ItemData> dataList = new List<ItemData>();//
for (int i = 0; i < HasItems.Length; i++)
{
if (HasItems[i])
{
string name = NameItems[i];
int quantity = Quantity[i];
int defence = DefenceItems[i];
ItemDataScript = new ItemData(name, quantity, defence);
items.Add(ItemDataScript);
string json = JsonUtility.ToJson(items);//
File.WriteAllText(Path.Combine(Application.persistentDataPath, "/items.json"), json);
}
}
items.Clear();
string filePath = Path.Combine(Application.persistentDataPath, "/items.json");
if (File.Exists(filePath))
{
string json = File.ReadAllText(filePath);
items = JsonUtility.FromJson<List<ItemData>>(json);
foreach (ItemData data in items)//
{
int index = GetIndex(data.Name);
if (index != -1)
{
HasItems[index] = true;
SetQuantity(data.Name, data.Quantity);
Debug.Log("Ok");
}
else
{
Debug.Log("fail");
}
}
}
}
The check in the download method at foreach is not output to the console.
Time to start debugging! Here is how you can begin your exciting new debugging adventures:
You must find a way to get the information you need in order to reason about what the problem is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
What is often happening in these cases is one of the following:
the code you think is executing is not actually executing at all
the code is executing far EARLIER or LATER than you think
the code is executing far LESS OFTEN than you think
the code is executing far MORE OFTEN than you think
the code is executing on another GameObject than you think it is
you’re getting an error or warning and you haven’t noticed it in the console window
To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.
Doing this should help you answer these types of questions:
is this code even running? which parts are running? how often does it run? what order does it run in?
what are the names of the GameObjects or Components involved?
what are the values of the variables involved? Are they initialized? Are the values reasonable?
are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)
Knowing this information will help you reason about the behavior you are seeing.
You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);
If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.
You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.
You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.
You could also just display various important quantities in UI Text elements to watch them change as you play the game.
Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654
If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.
Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.
Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:
When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls new to make one, it cannot make the native engine portion of the object.
Instead you must first create the MonoBehaviour using AddComponent() on a GameObject instance, or use ScriptableObject.CreateInstance() to make your SO, then use the appropriate JSON “populate object” call to fill in its public fields.
If you want to use PlayerPrefs to save your game, it’s always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:
Do not use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.
A few more notes about inventories:
These things (inventory, shop systems, character customization, dialog tree systems, crafting, etc) are fairly tricky hairy beasts, definitely deep in advanced coding territory.
Inventory code never lives “all by itself.” All inventory code is EXTREMELY tightly bound to prefabs and/or assets used to display and present and control the inventory. Problems and solutions must consider both code and assets as well as scene / prefab setup and connectivity.
Inventories / shop systems / character selectors all contain elements of:
a database of items that you may possibly possess / equip
a database of the items that you actually possess / equip currently
perhaps another database of your “storage” area at home base?
persistence of this information to storage between game runs
presentation of the inventory to the user (may have to scale and grow, overlay parts, clothing, etc)
interaction with items in the inventory or on the character or in the home base storage area
interaction with the world to get items in and out
dependence on asset definition (images, etc.) for presentation
Just the design choices of such a system can have a lot of complicating confounding issues, such as:
can you have multiple items? Is there a limit?
if there is an item limit, what is it? Total count? Weight? Size? Something else?
are those items shown individually or do they stack?
are coins / gems stacked but other stuff isn’t stacked?
do items have detailed data shown (durability, rarity, damage, etc.)?
can users combine items to make new items? How? Limits? Results? Messages of success/failure?
can users substantially modify items with other things like spells, gems, sockets, etc.?
does a worn-out item (shovel) become something else (like a stick) when the item wears out fully?
etc.
Your best bet is probably to write down exactly what you want feature-wise. It may be useful to get very familiar with an existing game so you have an actual example of each feature in action.
Once you have decided a baseline design, fully work through two or three different inventory tutorials on Youtube, perhaps even for the game example you have chosen above.
If you want to see most of the steps involved, make a “micro inventory” in your game, something whereby the player can have (or not have) a single item, and display that item in the UI, and let the user select that item and do things with it (take, drop, use, wear, eat, sell, buy, etc.).
Everything you learn doing that “micro inventory” of one item will apply when you have any larger more complex inventory, and it will give you a feel for what you are dealing with.
I have already solved my problem, I just saw your message.
JSON didn’t accept my List. I had to make a separate class.
Thank you very much for the detailed answer, I will definitely use this information and the links that you provided.