Advertisement
Guest User

Save and load a byte Array in Unity 3D

a guest
Apr 19th, 2016
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.99 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.     Esse exemplo demonstra como salvar e carregar um “byte array” com mais de 200.000 elementos usando “PlayerPrefs” (Utniy 3D) de maneira relativamente rápida.
  14.     Quando você salvar ou carregar um “byte array” muito grande o jogo pode congelar um pouco e depois volta ao normal.
  15.     Neste exemplo estamos salvando e carregando uma imagem. Quanto maior for a altura e largura da imagem maior vai ser o "byte array" e maior vai ser o tempo de congelamento do jogo.
  16.     Você pode modificar esse exemplo para salvar outros tipos de array(string, int, float e etc...) .
  17.  
  18.     Meu blogger:  http://jeffersonreis-portfolio.blogspot.com.br/
  19.  
  20.     Licença:
  21.     CC0 1.0 Universal (CC0 1.0)
  22.     Dedicação ao Domínio Público
  23.  
  24.     https://creativecommons.org/publicdomain/zero/1.0/deed.pt_BR
  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.         //Transforma cada elemento do byte[](array) em um elemento do XML
  85.         doc.Add(new XElement("root", byteArray.Select(x => new XElement("item", x))));
  86.  
  87.         //Deixa todo o string em uma linha
  88.         string xmlString = AllStringToOneLine(doc.ToString());
  89.  
  90.         //------------------------------------------------------
  91.         //Número máximo de "char"/letra dentro de uma linha na string
  92.         int LineLengthMax = 200000;
  93.         //Calcula o número de quebra de linhas
  94.         int NumberBreaklines = (xmlString.Length / LineLengthMax);
  95.         //Debug.Log("NumberBreaklines: " + NumberBreaklines);
  96.         //vamos pegar as posições onde vamos colocar a quebra de linha      
  97.         for (int i = 1; i <= NumberBreaklines; i++)
  98.         {
  99.             //Calcula onde a quebra de linha vai ser inserida
  100.             int x = LineLengthMax * i;
  101.             //Criamos quebras de linhas em várias posições da string.
  102.             xmlString = xmlString.Insert(x, "\n");
  103.         }
  104.         //------------------------------------------------------
  105.  
  106.         //Transforma cada linha em um elemento da "List"
  107.         idList = xmlString.Split(new[] { "\n" }, StringSplitOptions.None).ToList();
  108.  
  109.         //Salva Todos os elementos do List/Array
  110.         for (int i = 0; i <= idList.ToArray().Length - 1; i++)
  111.         {
  112.             //Salva a informação em bytes(número) em formato de texto/XML;
  113.             PlayerPrefs.SetString(key + i, idList[i]);
  114.         }
  115.         //Salva o número de elementos do 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.         //carrega o número de linhas
  127.         int a = PlayerPrefs.GetInt(key + "size");
  128.         for (int i = 0; i <= a - 1; i++)
  129.         {
  130.             //Carrega toda a informação em bytes(número) em formato de texto/XML
  131.             loadedStr += PlayerPrefs.GetString(key + i);
  132.         }
  133.  
  134.         //Transforma o texto em um documento XML
  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.         //Transforma cada elemento do XML em um elemnto para a "var array int"
  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.         //Transforma cada elemento do "array int" em um elemnto para a "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 os espaços em exesso;
  166.         Regex rgx = new Regex("\\s+");
  167.         // substitui multiplos espaços por um espaço
  168.         return word = rgx.Replace(word, charRepalcedSpace);
  169.     }
  170.  
  171.  
  172. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement