Daniel Roca Lopez Daniel Roca Lopez - 18 days ago 4
C# Question

Link data to gameobject in unity

I have a script that calculates something related to a mesh of a unity's gameobject. That information is saved into a dictionary but this info wont change for that mesh. The problem is, playing, stoping and playing again makes me recalculate that info. Is there a way to keep that dictionary like the gameobject keeps the mesh?

Answer

There are many ways to store data in Unity. I can think of these:

  1. PlayerPrefs. The easiest way and only supports basic data types. however read and write is costly and should avoided in update methods. This can be done using var i = PlayerPrefs.GetInt("myInt", 0) or PlayerPrefs.SetInt("myInt", newValue);

  2. Database. maybe the most difficult way but also most efficient if working with tons of data.

  3. Serialization. Unity uses serialization by default. it stores them as meta data in Plain Text format or Binary format or Both (your choice).

  4. JSONObject. Most flexible, customizable, portable and reliable. This is a better replacement for Serialized data. JSONObject files should be put in StreamingAssets folder and then copy to Application DataPath. In order to make this work you need a JSONObject class (can be found on the internet) and converters which you can write for your project to convert back and forth to/from JSONObject.

please correct me if I'm wrong.

This is my suggestion to your problem:

Make use of Unity Editor. Create a script derived from EditorWindow. Open its custom window it in your project. In that window make it so that when you select an object and click on a button, a JSONObject is generated and stored in the StreamingAssets folder. This way you have all the JSONObjects ready when your project is played or restarted.