PlayerPrefs存储Vector3等结构数据

发表于2017-10-12
评论0 589浏览

PlayerPrefs如何存储Vector3等结构数据,通常做法是使用json序列化、反序列化,如果不了解PlayerPrefs存储Vector3等结构数据的可以看看。

 

下面就写出两种(都是只能变成字符串)

1json的序列化、反序列化方式

JsonFx.Json.JsonReader.Deserialize(data);

JsonFx.Json.JsonWriter.Serialize(classObject);

 

使用了插件: JsonFx.dll

下面是使用的一个案例

 

  1. using UnityEngine;  
  2.   
  3. using System.Collections;  
  4.   
  5. using System.Collections.Generic;  
  6.   
  7.    
  8.   
  9. public class DataManager : MonoBehaviour  
  10.   
  11. {  
  12.   
  13.    
  14.   
  15. //sets the different kind of data into the player prefs...  
  16.   
  17.    
  18.   
  19. //sets the coins data(position and rotation)...  
  20.   
  21. public void setCoinsData(GameObject coins)  
  22.   
  23. {  
  24.   
  25. int coinCounter = 0;  
  26.   
  27. for (int i = 0; i < coins.transform.childCount; i )  
  28.   
  29. {  
  30.   
  31. coinCounter ;  
  32.   
  33. string key = coins.name   ""   coinCounter;  
  34.   
  35. //Coins Tag,Position,Rotation are passed in the Constructor.  
  36.   
  37. CoinsData coinData = new CoinsData(key, coins.transform.GetChild(i).position, coins.transform.GetChild(i).rotation);  
  38.   
  39. //String data stores data  
  40.   
  41. string data = JsonFx.Json.JsonWriter.Serialize(coinData);  
  42.   
  43. // Finally storing my Data i.e parsed from jason parser in Player Prefs  
  44.   
  45. PlayerPrefs.SetString(coins.tag   ""   coinCounter, data);  
  46.   
  47.    
  48.   
  49. }  
  50.   
  51. }  
  52.   
  53.    
  54.   
  55. //gets the activated gold coins data(position and rotation)...  
  56.   
  57. public GameObject getCoinsData()  
  58.   
  59. {  
  60.   
  61. GameObject coins = GameObject.FindGameObjectWithTag("Coin");  
  62.   
  63. for (int i = 0; i < coins.transform.childCount; i ) { if (coinCounter > 0)  
  64.   
  65. {  
  66.   
  67. string data = PlayerPrefs.GetString(coins.tag   ""   coinCounter);  
  68.   
  69. // Storing Vector3 Data in Jason.  
  70.   
  71. CoinsData coinData = JsonFx.Json.JsonReader.Deserialize(data);  
  72.   
  73. string key = coins.name   ""   coinCounter;  
  74.   
  75. coinData.coinPositionData = coinData.data [key];  
  76.   
  77. // Get Coin data.  
  78.   
  79. coins.transform.GetChild(i).position = new Vector3(coinData.coinPositionData.position.x, coinData.coinPositionData.position.y, coinData.coinPositionData.position.z);  
  80.   
  81. coins.transform.GetChild(i).rotation = new Quaternion(coinData.coinPositionData.rotation.x, coinData.coinPositionData.rotation.y, coinData.coinPositionData.rotation.z, coinData.coinPositionData.rotation.w);  
  82.   
  83. coins.transform.GetChild(i).gameObject.SetActive(true);  
  84.   
  85. coinCounter--;  
  86.   
  87. else  
  88.   
  89. {  
  90.   
  91. coins.transform.GetChild(i).gameObject.SetActive(false);  
  92.   
  93. }  
  94.   
  95. }  
  96.   
  97. return coins;  
  98.   
  99. }  
  100.   
  101. class CoinsData  
  102.   
  103. {  
  104.   
  105. public PositionData coinPositionData = new PositionData();  
  106.   
  107. // Storing Coin Data in Dictonary.  
  108.   
  109. public Dictionary data = new Dictionary();  
  110.   
  111. public CoinsData(string key, Vector3 coinPosition, Quaternion coinRotation)  
  112.   
  113. {  
  114.   
  115. // Get popstion of coin at run time  
  116.   
  117. coinPositionData.position = new Cords(coinPosition.x, coinPosition.y, coinPosition.z);  
  118.   
  119. coinPositionData.rotation = new Rotation(coinRotation.x, coinRotation.y, coinRotation.z, coinRotation.w);  
  120.   
  121. // Add data to dictionary  
  122.   
  123. if (key != null)  
  124.   
  125. data.Add(key, coinPositionData);  
  126.   
  127. }  
  128.   
  129. // Default Constructer is needed when u r using Jason Parsing.  
  130.   
  131. public CoinsData()  
  132.   
  133. {  
  134.   
  135. }  
  136.   
  137. }  
  138.   
  139. //Get Coins Postion  
  140.   
  141. class PositionData  
  142.   
  143. {  
  144.   
  145. public Cords position;  
  146.   
  147. public Rotation rotation;  
  148.   
  149. }  
  150.   
  151. // Get Coins Cords  
  152.   
  153. class Cords  
  154.   
  155. {  
  156.   
  157. public float x, y, z;  
  158.   
  159. public Cords(float x, float y, float z)  
  160.   
  161. {  
  162.   
  163. this.x = x;  
  164.   
  165. this.y = y;  
  166.   
  167. this.z = z;  
  168.   
  169. }  
  170.   
  171. public Cords()  
  172.   
  173. {  
  174.   
  175. }  
  176.   
  177. }  
  178.   
  179. // Get Coin Rotation  
  180.   
  181. class Rotation  
  182.   
  183. {  
  184.   
  185. public float x, y, z, w;  
  186.   
  187. public Rotation(float x, float y, float z, float w)  
  188.   
  189. {  
  190.   
  191. this.x = x;  
  192.   
  193. this.y = y;  
  194.   
  195. this.z = z;  
  196.   
  197. this.w = w;  
  198.   
  199. }  
  200.   
  201. public Rotation()  
  202.   
  203. {  
  204.   
  205. }  
  206.   
  207. }  
  208.   
  209. }  


 

注: 当然了可以使用  Unity5.2/3之后添加  JsonUtility  类, 更加方便!!!

 

 

2、自己写一个 一个形式

比如我们在存储一个数组  ,就是把每个元素  |”连接成一个字符串,

读取获取的时候在  根据 |”截取每个元素就行了 。原理就是这样。

http://wiki.unity3d.com/index.php/ArrayPrefs2

 

        尽管这些功能使它易于保存数组,PlayerPrefs 更适合少量的数据,像本地存储少于十个列表等。 PlayerPrefsX 并不打算把 PlayerPrefs 变成一个数据库系统。如果你有大量的数据,您应改用标准磁盘 IO 功能。

 

        PlayerPrefsX 是基于 PlayerPrefs.SetString,保存为一个数组(具体而言,一个字符数组)。所以,保存浮点数和整数的数组时,每个数字转换为 4 个字节,并存储到字节数组中。总字节数组转换成 base64,然后另存为一个字符串。当保存一个布尔值数组,每个布尔值被转换为一个字节数组,它再次转换为 base64 字符串,并保存在单个位。与字符串数组的字节数组索引是建造之初,其中的每个字节包含各自的字符串输入从字符串数组的长度。这是转换为 base64 字符串,然后在字符串数组中的所有条目都都融合成一个单一的字符串和追加到索引数组。

 

提供的类型都有:

  • PlayerPrefsX.SetBool
  • PlayerPrefsX.GetBool
  • PlayerPrefsX.SetLong (fixme: C# only)
  • PlayerPrefsX.GetLong (fixme: C# only)
  • PlayerPrefsX.SetVector2
  • PlayerPrefsX.GetVector2
  • PlayerPrefsX.SetVector3
  • PlayerPrefsX.GetVector3
  • PlayerPrefsX.SetQuaternion
  • PlayerPrefsX.GetQuaternion
  • PlayerPrefsX.SetColor
  • PlayerPrefsX.GetColor
  • PlayerPrefsX.SetIntArray
  • PlayerPrefsX.GetIntArray
  • PlayerPrefsX.SetFloatArray
  • PlayerPrefsX.GetFloatArray
  • PlayerPrefsX.SetBoolArray
  • PlayerPrefsX.GetBoolArray
  • PlayerPrefsX.SetStringArray
  • PlayerPrefsX.GetStringArray
  • PlayerPrefsX.SetVector2Array
  • PlayerPrefsX.GetVector2Array
  • PlayerPrefsX.SetVector3Array
  • PlayerPrefsX.GetVector3Array
  • PlayerPrefsX.SetQuaternionArray
  • PlayerPrefsX.GetQuaternionArray
  • PlayerPrefsX.SetColorArray
  • PlayerPrefsX.GetColorArray

 

比如 调用:

var coordinates = Vector2(.4,.2);
PlayerPrefsX.SetVector2 ("Coords", coordinates);

 

或者:

var aList = new List.<int>();
for (i = 0; i < 10; i ) aList.Add(i);
var anArray : int[] = aList.ToArray();
PlayerPrefsX.SetIntArray ("Numbers", anArray);

 

var numberArray = PlayerPrefsX.GetIntArray("Numbers");

 

具体代码如下:

  1. using UnityEngine;  
  2.  using System;  
  3.  using System.Collections;  
  4.  using System.Collections.Generic;  
  5.     
  6.  public class PlayerPrefsX  
  7.  {  
  8.  static private int endianDiff1;  
  9.  static private int endianDiff2;  
  10.  static private int idx;  
  11.  static private byte [] byteBlock;  
  12.     
  13.  enum ArrayType {Float, Int32, Bool, String, Vector2, Vector3, Quaternion, Color}  
  14.     
  15.  public static bool SetBool ( String name, bool value)  
  16.  {  
  17.          try  
  18.          {  
  19.                  PlayerPrefs.SetInt(name, value? 1 : 0);  
  20.          }  
  21.          catch  
  22.          {  
  23.                  return false;  
  24.          }  
  25.          return true;  
  26.  }  
  27.     
  28.  public static bool GetBool (String name)  
  29.  {  
  30.          return PlayerPrefs.GetInt(name) == 1;  
  31.  }  
  32.     
  33.  public static bool GetBool (String name, bool defaultValue)  
  34.  {  
  35.          return (1==PlayerPrefs.GetInt(name, defaultValue?1:0));  
  36.  }  
  37.     
  38.  public static long GetLong(string key, long defaultValue)  
  39.  {  
  40.          int lowBits, highBits;  
  41.          SplitLong(defaultValue, out lowBits, out highBits);  
  42.          lowBits = PlayerPrefs.GetInt(key "_lowBits", lowBits);  
  43.          highBits = PlayerPrefs.GetInt(key "_highBits", highBits);  
  44.     
  45.          // unsigned, to prevent loss of sign bit.  
  46.          ulong ret = (uint)highBits;  
  47.          ret = (ret << 32);  
  48.          return (long)(ret | (ulong)(uint)lowBits);  
  49.  }  
  50.     
  51.  public static long GetLong(string key)  
  52.  {  
  53.          int lowBits = PlayerPrefs.GetInt(key "_lowBits");  
  54.          int highBits = PlayerPrefs.GetInt(key "_highBits");  
  55.     
  56.          // unsigned, to prevent loss of sign bit.  
  57.          ulong ret = (uint)highBits;  
  58.          ret = (ret << 32);  
  59.          return (long)(ret | (ulong)(uint)lowBits);  
  60.  }  
  61.     
  62.  private static void SplitLong(long input, out int lowBits, out int highBits)  
  63.  {  
  64.          // unsigned everything, to prevent loss of sign bit.  
  65.          lowBits = (int)(uint)(ulong)input;  
  66.          highBits = (int)(uint)(input >> 32);  
  67.  }  
  68.     
  69.  public static void SetLong(string key, long value)  
  70.  {  
  71.          int lowBits, highBits;  
  72.          SplitLong(value, out lowBits, out highBits);  
  73.          PlayerPrefs.SetInt(key "_lowBits", lowBits);  
  74.          PlayerPrefs.SetInt(key "_highBits", highBits);  
  75.  }  
  76.     
  77.  public static bool SetVector2 (String key, Vector2 vector)  
  78.  {  
  79.          return SetFloatArray(key, new float[]{vector.x, vector.y});  
  80. }  
  81.     
  82.  static Vector2 GetVector2 (String key)  
  83.  {  
  84.          var floatArray = GetFloatArray(key);  
  85.          if (floatArray.Length < 2)  
  86.          {  
  87.                  return Vector2.zero;  
  88.          }  
  89.          return new Vector2(floatArray[0], floatArray[1]);  
  90.  }  
  91.     
  92.  public static Vector2 GetVector2 (String key, Vector2 defaultValue)  
  93.  {  
  94.          if (PlayerPrefs.HasKey(key))  
  95.          {  
  96.                  return GetVector2(key);  
  97.          }  
  98.          return defaultValue;  
  99.  }  
  100.     
  101.  public static bool SetVector3 (String key, Vector3 vector)  
  102.  {  
  103.          return SetFloatArray(key, new float []{vector.x, vector.y, vector.z});  
  104.  }  
  105.     
  106.  public static Vector3 GetVector3 (String key)  
  107.  {  
  108.          var floatArray = GetFloatArray(key);  
  109.          if (floatArray.Length < 3)  
  110.          {  
  111.                  return Vector3.zero;  
  112.          }  
  113.          return new Vector3(floatArray[0], floatArray[1], floatArray[2]);  
  114.  }  
  115.     
  116.  public static Vector3 GetVector3 (String key, Vector3 defaultValue)  
  117.  {  
  118.          if (PlayerPrefs.HasKey(key))  
  119.          {  
  120.                  return GetVector3(key);  
  121.          }  
  122.          return defaultValue;  
  123.  }  
  124.     
  125.  public static bool SetQuaternion (String key, Quaternion vector)  
  126.  {  
  127.          return SetFloatArray(key, new float[]{vector.x, vector.y, vector.z, vector.w});  
  128.  }  
  129.     
  130.  public static Quaternion GetQuaternion (String key)  
  131.  {  
  132.          var floatArray = GetFloatArray(key);  
  133.          if (floatArray.Length < 4)  
  134.          {  
  135.                  return Quaternion.identity;  
  136.          }  
  137.          return new Quaternion(floatArray[0], floatArray[1], floatArray[2], floatArray[3]);  
  138.  }  
  139.     
  140.  public static Quaternion GetQuaternion (String key, Quaternion defaultValue )  
  141.  {  
  142.          if (PlayerPrefs.HasKey(key))  
  143.          {  
  144.                  return GetQuaternion(key);  
  145.          }  
  146.          return defaultValue;  
  147.  }  
  148.     
  149.  public static bool SetColor (String key, Color color)  
  150.  {  
  151.          return SetFloatArray(key, new float[]{color.r, color.g, color.b, color.a});  
  152.  }  
  153.     
  154.  public static Color GetColor (String key)  
  155.  {  
  156.          var floatArray = GetFloatArray(key);  
  157.          if (floatArray.Length < 4)  
  158.          {  
  159.                  return new Color(0.0f, 0.0f, 0.0f, 0.0f);  
  160.          }  
  161.          return new Color(floatArray[0], floatArray[1], floatArray[2], floatArray[3]);  
  162.  }  
  163.     
  164.  public static Color GetColor (String key , Color defaultValue )  
  165.  {  
  166.          if (PlayerPrefs.HasKey(key))  
  167.          {  
  168.                  return GetColor(key);  
  169.          }  
  170.          return defaultValue;  
  171.  }  
  172.     
  173.  public static bool SetBoolArray (String key, bool[] boolArray)  
  174.  {  
  175.          // Make a byte array that's a multiple of 8 in length, plus 5 bytes to store the number of entries as an int32 (  identifier)  
  176.          // We have to store the number of entries, since the boolArray length might not be a multiple of 8, so there could be some padded zeroes  
  177.          var bytes = new byte[(boolArray.Length   7)/8   5];  
  178.          bytes[0] = System.Convert.ToByte (ArrayType.Bool);        // Identifier  
  179.          var bits = new BitArray(boolArray);  
  180.          bits.CopyTo (bytes, 5);  
  181.          Initialize();  
  182.          ConvertInt32ToBytes (boolArray.Length, bytes); // The number of entries in the boolArray goes in the first 4 bytes  
  183.     
  184.          return SaveBytes (key, bytes);          
  185.  }  
  186.     
  187.  public static bool[] GetBoolArray (String key)  
  188.  {  
  189.          if (PlayerPrefs.HasKey(key))  
  190.          {  
  191.                  var bytes = System.Convert.FromBase64String (PlayerPrefs.GetString(key));  
  192.                  if (bytes.Length < 5)  
  193.                  {  
  194.                          Debug.LogError ("Corrupt preference file for "   key);  
  195.                          return new bool[0];  
  196.                  }  
  197.                  if ((ArrayType)bytes[0] != ArrayType.Bool)  
  198.                  {  
  199.                          Debug.LogError (key   " is not a boolean array");  
  200.                          return new bool[0];  
  201.                  }  
  202.                  Initialize();  
  203.     
  204.                  // Make a new bytes array that doesn't include the number of entries   identifier (first 5 bytes) and turn that into a BitArray  
  205.                  var bytes2 = new byte[bytes.Length-5];  
  206.                  System.Array.Copy(bytes, 5, bytes2, 0, bytes2.Length);  
  207.                  var bits = new BitArray(bytes2);  
  208.                  // Get the number of entries from the first 4 bytes after the identifier and resize the BitArray to that length, then convert it to a boolean array  
  209.                  bits.Length = ConvertBytesToInt32 (bytes);  
  210.                  var boolArray = new bool[bits.Count];  
  211.                  bits.CopyTo (boolArray, 0);  
  212.     
  213.                  return boolArray;  
  214.          }  
  215.          return new bool[0];  
  216.  }  
  217.     
  218.  public static bool[] GetBoolArray (String key, bool defaultValue, int defaultSize)   
  219.  {  
  220.          if (PlayerPrefs.HasKey(key))  
  221.          {  
  222.                  return GetBoolArray(key);  
  223.          }  
  224.          var boolArray = new bool[defaultSize];  
  225.          for(int i=0;i<defaultSize;i )  
  226.          {  
  227.                  boolArray[i] = defaultValue;  
  228.          }  
  229.          return boolArray;  
  230.  }  
  231.     
  232.  public static bool SetStringArray (String key, String[] stringArray)  
  233.  {  
  234.          var bytes = new byte[stringArray.Length   1];  
  235.          bytes[0] = System.Convert.ToByte (ArrayType.String);        // Identifier  
  236.          Initialize();  
  237.     
  238.          // Store the length of each string that's in stringArray, so we can extract the correct strings in GetStringArray  
  239.          for (var i = 0; i < stringArray.Length; i )  
  240.          {  
  241.                  if (stringArray[i] == null)  
  242.                  {  
  243.                          Debug.LogError ("Can't save null entries in the string array when setting "   key);  
  244.                          return false;  
  245.                  }  
  246.                  if (stringArray[i].Length > 255)  
  247.                  {  
  248.                          Debug.LogError ("Strings cannot be longer than 255 characters when setting "   key);  
  249.                          return false;  
  250.                  }  
  251.                  bytes[idx ] = (byte)stringArray[i].Length;  
  252.          }  
  253.     
  254.          try  
  255.          {  
  256.                  PlayerPrefs.SetString (key, System.Convert.ToBase64String (bytes)   "|"   String.Join("", stringArray));  
  257.          }  
  258.          catch  
  259.          {  
  260.                  return false;  
  261.          }  
  262.          return true;  
  263.  }  
  264.     
  265.  public static String[] GetStringArray (String key)  
  266.  {  
  267.          if (PlayerPrefs.HasKey(key)) {  
  268.                  var completeString = PlayerPrefs.GetString(key);  
  269.                  var separatorIndex = completeString.IndexOf("|"[0]);  
  270.                  if (separatorIndex < 4) {  
  271.                          Debug.LogError ("Corrupt preference file for "   key);  
  272.                          return new String[0];  
  273.                  }  
  274.                  var bytes = System.Convert.FromBase64String (completeString.Substring(0, separatorIndex));  
  275.                  if ((ArrayType)bytes[0] != ArrayType.String) {  
  276.                          Debug.LogError (key   " is not a string array");  
  277.                          return new String[0];  
  278.                  }  
  279.                  Initialize();  
  280.     
  281.                  var numberOfEntries = bytes.Length-1;  
  282.                  var stringArray = new String[numberOfEntries];  
  283.                  var stringIndex = separatorIndex   1;  
  284.                  for (var i = 0; i < numberOfEntries; i )  
  285.                  {  
  286.                          int stringLength = bytes[idx ];  
  287.                          if (stringIndex   stringLength > completeString.Length)  
  288.                          {  
  289.                                  Debug.LogError ("Corrupt preference file for "   key);  
  290.                                  return new String[0];  
  291.                          }  
  292.                          stringArray[i] = completeString.Substring(stringIndex, stringLength);  
  293.                         stringIndex  = stringLength;  
  294.                  }  
  295.     
  296.                  return stringArray;  
  297.          }  
  298.          return new String[0];  
  299.  }  
  300.     
  301.  public static String[] GetStringArray (String key, String defaultValue, int defaultSize)  
  302.  {  
  303.          if (PlayerPrefs.HasKey(key))  
  304.          {  
  305.                  return GetStringArray(key);  
  306.          }  
  307.          var stringArray = new String[defaultSize];  
  308.          for(int i=0;i<defaultSize;i )  
  309.          {  
  310.                  stringArray[i] = defaultValue;  
  311.          }  
  312.          return stringArray;  
  313.  }  
  314.     
  315.  public static bool SetIntArray (String key, int[] intArray)  
  316.  {  
  317.          return SetValue (key, intArray, ArrayType.Int32, 1, ConvertFromInt);  
  318.  }  
  319.     
  320.  public static bool SetFloatArray (String key, float[] floatArray)  
  321.  {  
  322.          return SetValue (key, floatArray, ArrayType.Float, 1, ConvertFromFloat);  
  323.  }  
  324.     
  325.  public static bool SetVector2Array (String key, Vector2[] vector2Array )  
  326.  {  
  327.          return SetValue (key, vector2Array, ArrayType.Vector2, 2, ConvertFromVector2);  
  328.  }  
  329.     
  330.  public static bool SetVector3Array (String key, Vector3[] vector3Array)  
  331.  {  
  332.          return SetValue (key, vector3Array, ArrayType.Vector3, 3, ConvertFromVector3);  
  333.  }  
  334.     
  335.  public static bool SetQuaternionArray (String key, Quaternion[] quaternionArray )  
  336.  {  
  337.          return SetValue (key, quaternionArray, ArrayType.Quaternion, 4, ConvertFromQuaternion);  
  338.  }  
  339.     
  340.  public static bool SetColorArray (String key, Color[] colorArray)  
  341.  {  
  342.          return SetValue (key, colorArray, ArrayType.Color, 4, ConvertFromColor);  
  343.  }  
  344.     
  345.  private static bool SetValue<T> (String key, T array, ArrayType arrayType, int vectorNumber, Action<T, byte[],int> convert) where T : IList  
  346.  {  
  347.          var bytes = new byte[(4*array.Count)*vectorNumber   1];  
  348.          bytes[0] = System.Convert.ToByte (arrayType);        // Identifier  
  349.          Initialize();  
  350.     
  351.          for (var i = 0; i < array.Count; i ) {  
  352.                  convert (array, bytes, i);          
  353.          }  
  354.          return SaveBytes (key, bytes);  
  355.  }  
  356.     
  357.  private static void ConvertFromInt (int[] array, byte[] bytes, int i)  
  358.  {  
  359.          ConvertInt32ToBytes (array[i], bytes);  
  360.  }  
  361.     
  362.  private static void ConvertFromFloat (float[] array, byte[] bytes, int i)  
  363.  {  
  364.          ConvertFloatToBytes (array[i], bytes);  
  365.  }  
  366.     
  367.  private static void ConvertFromVector2 (Vector2[] array, byte[] bytes, int i)  
  368.  {  
  369.          ConvertFloatToBytes (array[i].x, bytes);  
  370.          ConvertFloatToBytes (array[i].y, bytes);  
  371.  }  
  372.     
  373.  private static void ConvertFromVector3 (Vector3[] array, byte[] bytes, int i)  
  374.  {  
  375.          ConvertFloatToBytes (array[i].x, bytes);  
  376.          ConvertFloatToBytes (array[i].y, bytes);  
  377.          ConvertFloatToBytes (array[i].z, bytes);  
  378.  }  
  379.     
  380.  private static void ConvertFromQuaternion (Quaternion[] array, byte[] bytes, int i)  
  381.  {  
  382.          ConvertFloatToBytes (array[i].x, bytes);  
  383.          ConvertFloatToBytes (array[i].y, bytes);  
  384.          ConvertFloatToBytes (array[i].z, bytes);  
  385.          ConvertFloatToBytes (array[i].w, bytes);  
  386.  }  
  387.     
  388.  private static void ConvertFromColor (Color[] array, byte[] bytes, int i)  
  389.  {  
  390.          ConvertFloatToBytes (array[i].r, bytes);  
  391.          ConvertFloatToBytes (array[i].g, bytes);  
  392.          ConvertFloatToBytes (array[i].b, bytes);  
  393.          ConvertFloatToBytes (array[i].a, bytes);  
  394.  }  
  395.     
  396.  public static int[] GetIntArray (String key)  
  397.  {  
  398.          var intList = new List<int>();  
  399.          GetValue (key, intList, ArrayType.Int32, 1, ConvertToInt);  
  400.          return intList.ToArray();  
  401.  }  
  402.     
  403.  public static int[] GetIntArray (String key, int defaultValue, int defaultSize)  
  404.  {  
  405.          if (PlayerPrefs.HasKey(key))  
  406.          {  
  407.                  return GetIntArray(key);  
  408.          }  
  409.          var intArray = new int[defaultSize];  
  410.          for (int i=0; i<defaultSize; i )  
  411.          {  
  412.                 intArray[i] = defaultValue;  
  413.          }  
  414.          return intArray;  
  415.  }  
  416.     
  417.  public static float[] GetFloatArray (String key)  
  418.  {  
  419.          var floatList = new List<float>();  
  420.          GetValue (key, floatList, ArrayType.Float, 1, ConvertToFloat);  
  421.          return floatList.ToArray();  
  422.  }  
  423.     
  424.  public static float[] GetFloatArray (String key, float defaultValue, int defaultSize)  
  425.  {  
  426.          if (PlayerPrefs.HasKey(key))  
  427.          {  
  428.                  return GetFloatArray(key);  
  429.          }  
  430.          var floatArray = new float[defaultSize];  
  431.          for (int i=0; i<defaultSize; i )  
  432.          {  
  433.                  floatArray[i] = defaultValue;  
  434.          }  
  435.          return floatArray;  
  436.  }  
  437.     
  438.  public static Vector2[] GetVector2Array (String key)  
  439.  {  
  440.          var vector2List = new List<Vector2>();  
  441.          GetValue (key, vector2List, ArrayType.Vector2, 2, ConvertToVector2);  
  442.          return vector2List.ToArray();  
  443.  }  
  444.     
  445.  public static Vector2[] GetVector2Array (String key, Vector2 defaultValue, int defaultSize)  
  446.  {  
  447.          if (PlayerPrefs.HasKey(key))  
  448.          {  
  449.                  return GetVector2Array(key);  
  450.          }  
  451.          var vector2Array = new Vector2[defaultSize];  
  452.          for(int i=0; i< defaultSize;i )  
  453.          {  
  454.                  vector2Array[i] = defaultValue;  
  455.          }  
  456.          return vector2Array;  
  457.  }  
  458.     
  459.  public static Vector3[] GetVector3Array (String key)  
  460.  {  
  461.          var vector3List = new List<Vector3>();  
  462.          GetValue (key, vector3List, ArrayType.Vector3, 3, ConvertToVector3);  
  463.          return vector3List.ToArray();  
  464.  }  
  465.     
  466.  public static Vector3[] GetVector3Array (String key, Vector3 defaultValue, int defaultSize)  
  467.  {  
  468.          if (PlayerPrefs.HasKey(key))  
  469.     
  470.          {  
  471.                  return GetVector3Array(key);  
  472.          }  
  473.          var vector3Array = new Vector3[defaultSize];  
  474.          for (int i=0; i<defaultSize;i )  
  475.          {  
  476.                  vector3Array[i] = defaultValue;  
  477.          }  
  478.          return vector3Array;  
  479.  }  
  480.     
  481.  public static Quaternion[] GetQuaternionArray (String key)  
  482.  {  
  483.          var quaternionList = new List<Quaternion>();  
  484.          GetValue (key, quaternionList, ArrayType.Quaternion, 4, ConvertToQuaternion);  
  485.          return quaternionList.ToArray();  
  486.  }  
  487.     
  488.  public static Quaternion[] GetQuaternionArray (String key, Quaternion defaultValue, int defaultSize)  
  489.  {  
  490.          if (PlayerPrefs.HasKey(key))  
  491.          {  
  492.                  return GetQuaternionArray(key);  
  493.          }  
  494.          var quaternionArray = new Quaternion[defaultSize];  
  495.          for(int i=0;i<defaultSize;i )  
  496.          {  
  497.                  quaternionArray[i] = defaultValue;  
  498.          }  
  499.          return quaternionArray;  
  500.  }  
  501.     
  502.  public static Color[] GetColorArray (String key)  
  503.  {  
  504.          var colorList = new List<Color>();  
  505.          GetValue (key, colorList, ArrayType.Color, 4, ConvertToColor);  
  506.          return colorList.ToArray();  
  507.  }  
  508.     
  509.  public static Color[] GetColorArray (String key, Color defaultValue, int defaultSize)  
  510.  {  
  511.          if (PlayerPrefs.HasKey(key)) {  
  512.                 return GetColorArray(key);  
  513.          }  
  514.          var colorArray = new Color[defaultSize];  
  515.          for(int i=0;i<defaultSize;i )  
  516.          {  
  517.                  colorArray[i] = defaultValue;  
  518.          }  
  519.          return colorArray;  
  520.  }  
  521.     
  522.  private static void GetValue<T> (String key, T list, ArrayType arrayType, int vectorNumber, Action<T, byte[]> convert) where T : IList  
  523.  {  
  524.          if (PlayerPrefs.HasKey(key))  
  525.          {  
  526.                  var bytes = System.Convert.FromBase64String (PlayerPrefs.GetString(key));  
  527.                 if ((bytes.Length-1) % (vectorNumber*4) != 0)  
  528.                  {  
  529.                          Debug.LogError ("Corrupt preference file for "   key);  
  530.                          return;  
  531.                  }  
  532.                  if ((ArrayType)bytes[0] != arrayType)  
  533.                  {  
  534.                          Debug.LogError (key   " is not a "   arrayType.ToString()   " array");  
  535.                          return;  
  536.                  }  
  537.                  Initialize();  
  538.     
  539.                  var end = (bytes.Length-1) / (vectorNumber*4);  
  540.                  for (var i = 0; i < end; i )  
  541.                  {  
  542.                          convert (list, bytes);  
  543.                  }  
  544.          }  
  545.  }  
  546.     
  547.  private static void ConvertToInt (List<int> list, byte[] bytes)  
  548.  {  
  549.          list.Add (ConvertBytesToInt32(bytes));  
  550.  }  
  551.     
  552.  private static void ConvertToFloat (List<float> list, byte[] bytes)  
  553.  {  
  554.          list.Add (ConvertBytesToFloat(bytes));  
  555.  }  
  556.     
  557.  private static void ConvertToVector2 (List<Vector2> list, byte[] bytes)  
  558.  {  
  559.          list.Add (new Vector2(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes)));  
  560.  }  
  561.     
  562.  private static void ConvertToVector3 (List<Vector3> list, byte[] bytes)  
  563.  {  
  564.          list.Add (new Vector3(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes)));  
  565.  }  
  566.     
  567.  private static void ConvertToQuaternion (List<Quaternion> list,byte[] bytes)  
  568.  {  
  569.          list.Add (new Quaternion(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes)));  
  570.  }  
  571.     
  572.  private static void ConvertToColor (List<Color> list, byte[] bytes)  
  573.  {  
  574.          list.Add (new Color(ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes), ConvertBytesToFloat(bytes)));  
  575.  }  
  576.     
  577.  public static void ShowArrayType (String key)  
  578.  {  
  579.          var bytes = System.Convert.FromBase64String (PlayerPrefs.GetString(key));  
  580.          if (bytes.Length > 0)  
  581.          {  
  582.                  ArrayType arrayType = (ArrayType)bytes[0];  
  583.                  Debug.Log (key   " is a "   arrayType.ToString()   " array");  
  584.          }  
  585.  }  
  586.     
  587.  private static void Initialize ()  
  588.  {  
  589.          if (System.BitConverter.IsLittleEndian)  
  590.          {  
  591.                  endianDiff1 = 0;  
  592.                  endianDiff2 = 0;  
  593.          }  
  594.          else  
  595.          {  
  596.                  endianDiff1 = 3;  
  597.                  endianDiff2 = 1;  
  598.          }  
  599.          if (byteBlock == null)  
  600.          {  
  601.                  byteBlock = new byte[4];  
  602.          }  
  603.          idx = 1;  
  604.  }  
  605.     
  606.  private static bool SaveBytes (String key, byte[] bytes)  
  607.  {  
  608.          try  
  609.          {  
  610.                  PlayerPrefs.SetString (key, System.Convert.ToBase64String (bytes));  
  611.          }  
  612.          catch  
  613.          {  
  614.                  return false;  
  615.          }  
  616.          return true;  
  617.  }  
  618.     
  619.  private static void ConvertFloatToBytes (float f, byte[] bytes)  
  620.  {  
  621.          byteBlock = System.BitConverter.GetBytes (f);  
  622.          ConvertTo4Bytes (bytes);  
  623.  }  
  624.     
  625.  private static float ConvertBytesToFloat (byte[] bytes)  
  626.  {  
  627.          ConvertFrom4Bytes (bytes);  
  628.          return System.BitConverter.ToSingle (byteBlock, 0);  
  629.  }  
  630.     
  631.  private static void ConvertInt32ToBytes (int i, byte[] bytes)  
  632.  {  
  633.          byteBlock = System.BitConverter.GetBytes (i);  
  634.          ConvertTo4Bytes (bytes);  
  635.  }  
  636.     
  637.  private static int ConvertBytesToInt32 (byte[] bytes)  
  638.  {  
  639.         ConvertFrom4Bytes (bytes);  
  640.          return System.BitConverter.ToInt32 (byteBlock, 0);  
  641.  }  
  642.     
  643.  private static void ConvertTo4Bytes (byte[] bytes)  
  644.  {  
  645.          bytes[idx  ] = byteBlock[    endianDiff1];  
  646.          bytes[idx 1] = byteBlock[1   endianDiff2];  
  647.          bytes[idx 2] = byteBlock[2 - endianDiff2];  
  648.          bytes[idx 3] = byteBlock[3 - endianDiff1];  
  649.          idx  = 4;  
  650.  }  
  651.     
  652.  private static void ConvertFrom4Bytes (byte[] bytes)  
  653.  {  
  654.          byteBlock[    endianDiff1] = bytes[idx  ];  
  655.          byteBlock[1   endianDiff2] = bytes[idx 1];  
  656.          byteBlock[2 - endianDiff2] = bytes[idx 2];  
  657.          byteBlock[3 - endianDiff1] = bytes[idx 3];  
  658.          idx  = 4;  
  659.  }  
  660.  }  

 

 

还有 新的 针对 这个代码的封装如下:

  1. using UnityEngine;  
  2.  using System;  
  3.  using System.Linq;  
  4.  using System.Collections;  
  5.  using System.Collections.Generic;  
  6.  using System.Reflection;  
  7.     
  8.  public class PlayerPrefsX2   
  9.  {                  
  10.          public static T GetObject<T>(string key, T defaultValue) where T : new()  
  11.          {  
  12.                  Type t = typeof(T);  
  13.                  FieldInfo[] fieldInfos = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic |  
  14.                          BindingFlags.Instance | BindingFlags.Static |  
  15.                          BindingFlags.DeclaredOnly);  
  16.    
  17.                  var newObj = new T();  
  18.     
  19.                  foreach (var fieldInfo in fieldInfos)  
  20.                  {  
  21.                          var fieldName = fieldInfo.Name;  
  22.                          var fieldKey = string.Format("{0}-{1}-{2}", t, fieldInfo.MemberType, fieldName);  
  23.     
  24.                          if(fieldInfo.FieldType == typeof(int))  
  25.                          {  
  26.                                  var val = PlayerPrefs.GetInt (fieldKey);  
  27.                                  Debug.Log (val);  
  28.                                  fieldInfo.SetValue(newObj, (int)val);  
  29.                          }          
  30.                          else if(fieldInfo.FieldType == typeof(float))  
  31.                          {  
  32.                                  var val = PlayerPrefs.GetFloat (fieldKey);  
  33.                                  fieldInfo.SetValue(newObj, (float)val);  
  34.                          }  
  35.                          else if(fieldInfo.FieldType == typeof(string))  
  36.                          {  
  37.                                  var val = PlayerPrefs.GetString (fieldKey);  
  38.                                  fieldInfo.SetValue(newObj, (string)val);  
  39.                          }  
  40.                          else if(fieldInfo.FieldType == typeof(long))  
  41.                          {  
  42.                                  var val = PlayerPrefsX.GetLong (fieldKey);  
  43.                                  fieldInfo.SetValue(newObj, (long)val);  
  44.                          }  
  45.                          else if(fieldInfo.FieldType == typeof(Vector2))  
  46.                         {  
  47.                                  var val = PlayerPrefsX.GetVector2 (fieldKey, Vector2.zero);  
  48.                                  fieldInfo.SetValue(newObj, (Vector2)val);  
  49.                         }  
  50.                          else if(fieldInfo.FieldType == typeof(Quaternion))  
  51.                          {  
  52.                                  var val = PlayerPrefsX.GetQuaternion (fieldKey);  
  53.                                  fieldInfo.SetValue(newObj, (Quaternion)val);  
  54.                          }  
  55.                          else if(fieldInfo.FieldType == typeof(Color))  
  56.                          {  
  57.                                  var val = PlayerPrefsX.GetColor (fieldKey);  
  58.                                  fieldInfo.SetValue(newObj, (Color)val);  
  59.                          }  
  60.                          // array.  
  61.                          else if(fieldInfo.FieldType == typeof(int[]))  
  62.                          {  
  63.                                  var val = PlayerPrefsX.GetIntArray (fieldKey);  
  64.                                  fieldInfo.SetValue(newObj, (int[])val);  
  65.                          }  
  66.                          else if(fieldInfo.FieldType == typeof(float[]))  
  67.                         {  
  68.                                  var val = PlayerPrefsX.GetFloatArray (fieldKey);  
  69.                                  fieldInfo.SetValue(newObj, (float[])val);  
  70.                          }  
  71.                          else if(fieldInfo.FieldType == typeof(string[]))  
  72.                          {  
  73.                                  var val = PlayerPrefsX.GetStringArray (fieldKey);  
  74.                                  fieldInfo.SetValue(newObj, (string[])val);  
  75.                          }  
  76.                          else if(fieldInfo.FieldType == typeof(Quaternion[]))  
  77.                          {  
  78.                                  var val = PlayerPrefsX.GetQuaternionArray (fieldKey);  
  79.                                  fieldInfo.SetValue(newObj, (Quaternion[])val);  
  80.                          }  
  81.                          else if(fieldInfo.FieldType == typeof(Color[]))  
  82.                          {  
  83.                                  var val = PlayerPrefsX.GetColorArray (fieldKey);  
  84.                                  fieldInfo.SetValue(newObj, (Color[])val);  
  85.                          }  
  86.                          // list.  
  87.                          else if(fieldInfo.FieldType == typeof(List<int>))  
  88.                          {  
  89.                                  var val = PlayerPrefsX.GetIntArray (fieldKey);  
  90.                                  fieldInfo.SetValue(newObj, val.OfType<int>().ToList());  
  91.                          }  
  92.                          else if(fieldInfo.FieldType == typeof(List<float>))  
  93.                          {  
  94.                                  var val = PlayerPrefsX.GetFloatArray (fieldKey);  
  95.                                  fieldInfo.SetValue(newObj, val.OfType<float>().ToList());  
  96.                          }  
  97.                          else if(fieldInfo.FieldType == typeof(List<string>))  
  98.                          {  
  99.                                  var val = PlayerPrefsX.GetStringArray (fieldKey);  
  100.                                  fieldInfo.SetValue(newObj, val.OfType<string>().ToList());  
  101.                          }  
  102.                          else if(fieldInfo.FieldType == typeof(List<Quaternion>))  
  103.                          {  
  104.                                  var val = PlayerPrefsX.GetQuaternionArray (fieldKey);  
  105.                                  fieldInfo.SetValue(newObj, (Quaternion[])val);  
  106.                          }  
  107.                          else if(fieldInfo.FieldType == typeof(List<Color>))  
  108.                          {  
  109.                                  var val = PlayerPrefsX.GetColorArray (fieldKey);  
  110.                                  fieldInfo.SetValue(newObj, (Color[])val);  
  111.                          }  
  112.                          // other.  
  113.                          else  
  114.                          {  
  115.                                  Debug.LogError("Un known type.");  
  116.                          }  
  117.                  }  
  118.     
  119.                  if (newObj != null)  
  120.                  {  
  121.                          return newObj;  
  122.                  }  
  123.     
  124.                  return defaultValue;  
  125.          }  
  126.     
  127.          public static bool SetObject(string name, object value)  
  128.          {  
  129.                  Type t = value.GetType();  
  130.                  FieldInfo[] fieldInfos = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic |  
  131.                          BindingFlags.Instance | BindingFlags.Static |  
  132.                          BindingFlags.DeclaredOnly);  
  133.     
  134.                  try  
  135.                  {  
  136.                          foreach (var fieldInfo in fieldInfos)  
  137.                          {  
  138.                                  var fieldName = fieldInfo.Name;  
  139.                                  var fieldKey = string.Format("{0}-{1}-{2}-{3}", name, t, fieldInfo.MemberType, fieldName);  
  140.     
  141.                                  if(fieldInfo.FieldType == typeof(int))  
  142.                                  {  
  143.                                          var val = (int)fieldInfo.GetValue(value);  
  144.                                          PlayerPrefs.SetInt (fieldKey, val);  
  145.                                  }          
  146.                                  else if(fieldInfo.FieldType == typeof(float))  
  147.                                  {  
  148.                                          var val = (float)fieldInfo.GetValue(value);  
  149.                                          PlayerPrefs.SetFloat (fieldKey, val);  
  150.                                  }  
  151.                                  else if(fieldInfo.FieldType == typeof(string))  
  152.                                  {  
  153.                                          var val = (string)fieldInfo.GetValue(value);  
  154.                                          PlayerPrefs.SetString (fieldKey, val);  
  155.                                  }  
  156.                                  else if(fieldInfo.FieldType == typeof(long))  
  157.                                  {  
  158.                                          var val = (long)fieldInfo.GetValue(value);  
  159.                                          PlayerPrefsX.SetLong (fieldKey, val);  
  160.                                  }  
  161.                                  // Unity val.  
  162.                                 else if(fieldInfo.FieldType == typeof(Vector2))  
  163.                                  {  
  164.                                          var val = (Vector2)fieldInfo.GetValue(value);  
  165.                                          PlayerPrefsX.SetVector2 (fieldKey, val);  
  166.                                  }  
  167.                                  else if(fieldInfo.FieldType == typeof(Vector3))  
  168.                                  {  
  169.                                          var val = (Vector3)fieldInfo.GetValue(value);  
  170.                                          PlayerPrefsX.SetVector3 (fieldKey, val);  
  171.                                  }  
  172.                                  else if(fieldInfo.FieldType == typeof(Quaternion))  
  173.                                  {  
  174.                                          var val = (Quaternion)fieldInfo.GetValue(value);  
  175.                                          PlayerPrefsX.SetQuaternion (fieldKey, val);  
  176.                                  }  
  177.                                  else if(fieldInfo.FieldType == typeof(Color))  
  178.                                  {  
  179.                                          var val = (Color)fieldInfo.GetValue(value);  
  180.                                          PlayerPrefsX.SetColor (fieldKey, val);  
  181.                                  }  
  182.                                  // array.  
  183.                                  else if(fieldInfo.FieldType == typeof(int[]))  
  184.                                  {  
  185.                                          var val = (int[])fieldInfo.GetValue(value);  
  186.                                          PlayerPrefsX.SetIntArray (fieldKey, val);  
  187.                                  }  
  188.                                  else if(fieldInfo.FieldType == typeof(float[]))  
  189.                                  {  
  190.                                          var val = (float[])fieldInfo.GetValue(value);  
  191.                                          PlayerPrefsX.SetFloatArray (fieldKey, val);  
  192.                                  }  
  193.                                  else if(fieldInfo.FieldType == typeof(string[]))  
  194.                                  {  
  195.                                          var val = (string[])fieldInfo.GetValue(value);  
  196.                                          PlayerPrefsX.SetStringArray (fieldKey, val);  
  197.                                  }  
  198.                                  else if(fieldInfo.FieldType == typeof(Quaternion[]))  
  199.                                  {  
  200.                                          var val = (Quaternion[])fieldInfo.GetValue(value);  
  201.                                          PlayerPrefsX.SetQuaternionArray (fieldKey, val);  
  202.                                  }  
  203.                                  else if(fieldInfo.FieldType == typeof(Color[]))  
  204.                                  {  
  205.                                          var val = (Color[])fieldInfo.GetValue(value);  
  206.                                          PlayerPrefsX.SetColorArray (fieldKey, val);  
  207.                                  }  
  208.                                  // list.  
  209.                                  else if(fieldInfo.FieldType == typeof(List<int>))  
  210.                                  {  
  211.                                          var val = (List<int>)fieldInfo.GetValue(value);  
  212.                                          PlayerPrefsX.SetIntArray (fieldKey, val.ToArray());  
  213.                                  }  
  214.                                  else if(fieldInfo.FieldType == typeof(List<float>))  
  215.                                  {  
  216.                                          var val = (List<float>)fieldInfo.GetValue(value);  
  217.                                          PlayerPrefsX.SetFloatArray (fieldKey, val.ToArray());  
  218.                                  }  
  219.                                  else if(fieldInfo.FieldType == typeof(List<string>))  
  220.                                  {  
  221.                                          var val = (List<string>)fieldInfo.GetValue(value);  
  222.                                          PlayerPrefsX.SetStringArray (fieldKey, val.ToArray());  
  223.                                  }  
  224.                                  else if(fieldInfo.FieldType == typeof(List<Quaternion>))  
  225.                                  {  
  226.                                          var val = (Quaternion[])fieldInfo.GetValue(value);  
  227.                                          PlayerPrefsX.SetQuaternionArray (fieldKey, val.ToArray());  
  228.                                  }  
  229.                                  else if(fieldInfo.FieldType == typeof(List<Color>))  
  230.                                  {  
  231.                                          var val = (Color[])fieldInfo.GetValue(value);  
  232.                                          PlayerPrefsX.SetColorArray (fieldKey, val.ToArray());  
  233.                                  }  
  234.                                  else  
  235.                                  {  
  236.                                          Debug.LogError("Un known type.");  
  237.                                  }  
  238.                          }  
  239.                  }  
  240.                  catch  
  241.                  {  
  242.                          return false;  
  243.                  }  
  244.                  return true;  
  245.          }  
  246.  }  

 

 

测试如下:

  1. using UnityEngine;  
  2.  using System.Collections;  
  3.     
  4.  class Hoge  
  5.  {  
  6.          public string hogePub;  
  7.          public int intPub;  
  8.         private int bar;  
  9.          private string fuga;  
  10.          private string hoge;  
  11.  }  
  12.     
  13.  public class Test : MonoBehaviour  
  14.  {  
  15.          // Use this for initialization  
  16.          void Start ()  
  17.          {  
  18.     
  19.                  var hoge = new Hoge{hogePub="hoge", intPub=100};  
  20.                  PlayerPrefsX2.SetObject("test", hoge);  
  21.     
  22.                  var a = PlayerPrefsX2.GetObject<Hoge> ("test"null);  
  23.                  Debug.Log (a.hogePub);  
  24.                  Debug.Log (a.intPub);  
  25.          }  
  26.  }  
http://blog.csdn.net/u010019717/article/details/51025272

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

0个评论