Advertisement
Guest User

Save and load a byte Array in Unity 3D

a guest
Apr 19th, 2016
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.89 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text.RegularExpressions;
  7. using System.Xml.Linq;
  8. using System.Linq;
  9.  
  10.  
  11. /*
  12.  
  13.      This example demonstrates how to save and load a "byte array" with more than 200,000 elements using "PlayerPrefs" (3D Utniy) relatively quickly.
  14.      When you save or load a "byte array" very large, the game may freeze a bit and then back to normal.
  15.      In this example we are saving and loading an image. The greater the height and width of the image, the greater will be the "byte array" and the greater will be the game freezing time.
  16.      You can modify this example to save other types of array (string, int, float, etc ...).  
  17.  
  18.      My blog:  http://jeffersonreis-portfolio.blogspot.com.br/
  19.  
  20.      License:
  21.      CC0 1.0 Universal (CC0 1.0)
  22.      Public Domain Dedication
  23.  
  24.      https://creativecommons.org/publicdomain/zero/1.0/
  25.  
  26. */
  27.  
  28. public class SaveAndLoadByteArray : MonoBehaviour
  29. {
  30.  
  31.     public string imageURL = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
  32.     public Renderer rendererObj;
  33.     public bool imageToMainTexture = true;
  34.  
  35.     private string mykeySave = "byteArrayToXml";
  36.     private byte[] myByteArray;
  37.  
  38.  
  39.     // Use this for initialization
  40.     IEnumerator Start()
  41.     {
  42.         Debug.Log("Loading...");
  43.         WWW www = new WWW(imageURL);
  44.         yield return www;
  45.         Debug.Log("downloaded");
  46.         if (imageToMainTexture == true)
  47.         {
  48.             rendererObj.material.mainTexture = www.texture;
  49.             myByteArray = www.bytes;
  50.         }
  51.     }
  52.  
  53.     // Update is called once per frame
  54.     void Update()
  55.     {
  56.  
  57.         if (Input.GetKeyDown(KeyCode.S))
  58.         {
  59.             SaveByte(myByteArray, mykeySave);
  60.             Debug.Log("byte array length: " + myByteArray.Length);
  61.         }
  62.  
  63.         if (Input.GetKeyDown(KeyCode.L))
  64.         {
  65.             myByteArray = LoadBytes(mykeySave);
  66.             Debug.Log("byte array length: " + myByteArray.Length);
  67.             Texture2D tex = new Texture2D(2, 2);
  68.             tex.LoadImage(myByteArray);
  69.             rendererObj.material.mainTexture = tex;
  70.         }
  71.     }
  72.  
  73.  
  74.     void OnGUI()
  75.     {
  76.         GUI.Label(new Rect(10, 10, Screen.width, Screen.height), "Press \"S\" to save and \"L\" to load.");
  77.     }
  78.  
  79.     void SaveByte(byte[] byteArray, string key)
  80.     {
  81.         List<string> idList = new List<string>();
  82.         XDocument doc = new XDocument();
  83.  
  84.         //Transforms each element of the byte [] (array) on an element of the XML
  85.         doc.Add(new XElement("root", byteArray.Select(x => new XElement("item", x))));
  86.  
  87.         //Lets all string in a line
  88.         string xmlString = AllStringToOneLine(doc.ToString());
  89.  
  90.         //------------------------------------------------------
  91.         //Maximum number of "char" / letter within a row in the string
  92.         int LineLengthMax = 200000;
  93.         //Calculates the number of line breaks
  94.         int NumberBreaklines = (xmlString.Length / LineLengthMax);
  95.         //Debug.Log("NumberBreaklines: " + NumberBreaklines);
  96.         //let's take the positions where we put the line break      
  97.         for (int i = 1; i <= NumberBreaklines; i++)
  98.         {
  99.             //Calculate where the line break will be inserted
  100.             int x = LineLengthMax * i;
  101.             //We create line breaks in various positions of the string
  102.             xmlString = xmlString.Insert(x, "\n");
  103.         }
  104.         //------------------------------------------------------
  105.  
  106.         //Transform each line in an element of the "List"
  107.         idList = xmlString.Split(new[] { "\n" }, StringSplitOptions.None).ToList();
  108.  
  109.         //Saves all the elements of the List / Array
  110.         for (int i = 0; i <= idList.ToArray().Length - 1; i++)
  111.         {
  112.             //Saves the information in bytes (number) in text / XML
  113.             PlayerPrefs.SetString(key + i, idList[i]);
  114.         }
  115.         //Saves the number of elements of the List / Array
  116.         PlayerPrefs.SetInt(key + "size", idList.ToArray().Length);
  117.  
  118.         Debug.Log("saved");
  119.     }
  120.  
  121.  
  122.     byte[] LoadBytes(string key)
  123.     {
  124.         byte[] byteArray;
  125.         string loadedStr = "";
  126.         //reloads the number of lines
  127.         int a = PlayerPrefs.GetInt(key + "size");
  128.         for (int i = 0; i <= a - 1; i++)
  129.         {
  130.             //It carries all the information in bytes (number) in text / XML
  131.             loadedStr += PlayerPrefs.GetString(key + i);
  132.         }
  133.  
  134.         //Transforms the text into an XML document
  135.         XDocument doc = XDocument.Parse(loadedStr);
  136.  
  137.         // counts direct children of the root element          
  138.         //int childrenCount = doc.Root.Elements().Count();  
  139.         //Debug.Log("children Count: " + childrenCount);
  140.  
  141.         //=====================================================
  142.         //Turns every element of the XML an element to the "var int array"
  143.         var array = doc.Descendants("item").Select(x => (int)x).ToArray();
  144.         //Debug.Log("array index 0: " + array[0]);
  145.         //Debug.Log("array last index: " + array[array.Length - 1]);
  146.         //Debug.Log("var array size: " + array.Length);
  147.         //=====================================================
  148.  
  149.         //Transforms each element of the "int array" an element to the "byte array"
  150.         byteArray = array.Select(x => (byte)x).ToArray();
  151.         //Debug.Log("byteArray size: " + byteArray.Length);
  152.         //Debug.Log("byteArray index 0: " + byteArray[0]);
  153.         //Debug.Log("byteArray last index: " + byteArray[byteArray.Length - 1]);
  154.  
  155.         Debug.Log("Loaded");
  156.  
  157.         return byteArray;
  158.     }
  159.  
  160.  
  161.  
  162.     string AllStringToOneLine(string word)
  163.     {
  164.         string charRepalcedSpace = " ";
  165.         // Remove excess spaces
  166.         Regex rgx = new Regex("\\s+");
  167.         // replace multiple spaces by a space
  168.         return word = rgx.Replace(word, charRepalcedSpace);
  169.     }
  170.  
  171.  
  172. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement