How to cast a string to a specific type of object?
I want to make a PlayerPrefs wrapper where I can store whatever data I want.
so it goes like this
void Set<T>(string Key, T Value)
{
PlayerPrefs.SetString(Key, Value.ToString());
}
T Get<T>(string Key)// where T : IParseable
{
//Code that checks for errors and throws exceptions
return T.Parse(PlayerPrefs.GetString(Key));
}
The problem in this is that it "relies" on the data to be parseable (or implement IParseable that I invented XD) and primitive data types don't implement it even thought they all have a Parse
Method
Is there already an IParseable
interface I can use?
If not, is there a way to know if the T type is a primitive data type?
Is there a better way to achieve what I want to do?
Would it be better if I used JSON for this?
The comments are correct, you shouldn't be using ToString() and Parse. What you are doing (or trying to do) is serialization. Here are a couple of resources to look to for figuring out how to serialize and deserialize your data:
If you use one of the above examples, the data should be serialized to a human-readable format. It's less efficient, but serializing to a string is already less efficient than serializing to bytes. If you need that level of efficiency, you shouldn't be using PlayerPrefs.