How do I initialize my variables in such a way that there will be an initial variable (Ex. The price of an item but it goes up by 20% every time you purchase) and for the next time I load the game (Upon exiting and entering), the price that went up by 20% is the new initial variable.
Note: This is for an idle game for a school project. I already have a save system. The only problem I am currently working on is this initialization problem.
When initializing your variable, for example in Start, first attempt to load its value from your saving mechanism of choice. If you found a value, use that. Otherwise use your default. When updating the value or quitting the game, save the current value.
Don’t 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.
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:
Of course, I didn’t forget about the loading system. I have one as well. I think I figured it out tho. However, what my problem really was, is that when I load the game, instead of loading the recent data it would still use the value at the start function since it is at the start function. If that makes sense.
Now, the solution I have thought of is by using an if statement at the start function where it would check if there is a save file to load. If there is none, it would initialize the values again. Would that work?