- Home /
Question is off-topic or not relevant
Can't modify variable values of a serialized object unless its custom inspector is showing
I'm stuck with a strange problem i've never faced before. I have a Wallet
class, and it's variable is kept inside class WalletStorageFactory
like this:
public class WalletStorageFactory : MonoBehaviour
{
[SerializeField]
public Wallet _wallet;
}
The Wallet
class looks like this :
[Serializable]
public class Wallet
{
[HideInInspector]
[SerializeField]
public List<GameEntity> _entities;
}
and GameEntity
class looks like this :
[Serializable]
public class GameEntity
{
public string _id;
public int _balance;
}
I have a custom inspector for WalletStorageFactory
from which I can add GameEntities to its _wallet
. The _wallet
seems to be serializing well. But when I run my project, I can't make changes to a GameEntity
's balance field (via some OnGUI methods) UNLESS the WalletStorageFactory
gameObject is selected (and hence it's inspector showing). I even ran it on device, but the issue exists there as well. What am I doing wrong here?
Answer by Bunny83 · May 30, 2016 at 01:22 PM
Unity's serialization system only works in the editor. It can only serialize assets in the editor. It doesn't support serialization at runtime as assets in a built game are read only. The serialization of the AssetDatabase belongs to the editor code base.
If you want to serialize data at runtime you have to use your own way of storing / loading the data somewhere. Unity now has the JsonUtility class which is more or less compatible with Unity's serializer. You can use it to serialize your data as json and store it either in a file or use PlayerPrefs.
I was doing something terribly wrong. What I was doing wrong was that I was trying to keep reference of GameEntity, present inside wallet, in another class called EntityExchange against an exchange Id. This was resulting in two objects of the same GameEntity, with the same variable values being created, one inside wallet object, and the other in gameEntity exchange object. So when I was trying to get a GameEntity in an exchange, it wasn't returning the GameEntity inside Wallet. Ins$$anonymous$$d, it was returning its own GameEntity object that got serialized with it. Sorry for wasting your time. Closing the question. Thank you