- Home /
How to save run-time variables to dictionary?
I want to cache some calculations and save them to a dictionary (or similar data structure) during runtime. How can I do this? Thanks in advance.
Answer by _foa · Feb 28, 2015 at 08:27 PM
If you are using C# you can use a Dictionary data type and its method Add(Key, Value).
See: https://msdn.microsoft.com/en-GB/library/xfhwa508%28v=vs.110%29.aspx)
If you need more than one game object to access this Dictionary you can make the variable static so it is shared among game objects.
See: https://msdn.microsoft.com/en-GB/library/98f28cdx.aspx
Of course you need to attach a script with the Dictionary declaration to the game object or prefab that will use it.
If different game objects or prefabs needs to access the Dictionary you should move your Dictionary declaration to a separate static class in the Unity project Visual Studio (MonoDevelop) solution and use this class to access the Dictionary from different scripts.
I don't know how much you know C# and programming in general so if you need a more in depth explanation with an example let me know :)
I hope it helps !
I'm intermediately experienced with C# (watched all the Unity tutorials and made a few games) but I'm not very familiar with serialization and data storage. After getting the dictionary saved in an instance of a script, how can I save that to a file to be accessed in later runs?
I'm caching all the sine calculations for cross-platform deter$$anonymous$$ism and to help the performance of my game but I'm having trouble saving these cached calculations.
You can find a good and official source of examples and documentaion right here: https://msdn.microsoft.com/en-us/library/7ay27kt9(v=vs.110).aspx
One of the most common classes used to serialize data is https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx. Be aware that using the BinaryFormatter will make your data version dependent but in this case, if you do not require your data to be human readable, the BinaryFormatter can be used without problems because the Dictionary data structure will not be changed any time soon, so you do not need to worry about versioning problems.
Hope I've been clear, let me konw :)