Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- using System.Xml.Linq;
- using System.Linq;
- /*
- 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.
- Quando você salvar ou carregar um “byte array” muito grande o jogo pode congelar um pouco e depois volta ao normal.
- 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.
- Você pode modificar esse exemplo para salvar outros tipos de array(string, int, float e etc...) .
- Meu blogger: http://jeffersonreis-portfolio.blogspot.com.br/
- Licença:
- CC0 1.0 Universal (CC0 1.0)
- Dedicação ao Domínio Público
- https://creativecommons.org/publicdomain/zero/1.0/deed.pt_BR
- */
- public class SaveAndLoadByteArray : MonoBehaviour
- {
- public string imageURL = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
- public Renderer rendererObj;
- public bool imageToMainTexture = true;
- private string mykeySave = "byteArrayToXml";
- private byte[] myByteArray;
- // Use this for initialization
- IEnumerator Start()
- {
- Debug.Log("Loading...");
- WWW www = new WWW(imageURL);
- yield return www;
- Debug.Log("downloaded");
- if (imageToMainTexture == true)
- {
- rendererObj.material.mainTexture = www.texture;
- myByteArray = www.bytes;
- }
- }
- // Update is called once per frame
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.S))
- {
- SaveByte(myByteArray, mykeySave);
- Debug.Log("byte array length: " + myByteArray.Length);
- }
- if (Input.GetKeyDown(KeyCode.L))
- {
- myByteArray = LoadBytes(mykeySave);
- Debug.Log("byte array length: " + myByteArray.Length);
- Texture2D tex = new Texture2D(2, 2);
- tex.LoadImage(myByteArray);
- rendererObj.material.mainTexture = tex;
- }
- }
- void OnGUI()
- {
- GUI.Label(new Rect(10, 10, Screen.width, Screen.height), "Press \"S\" to save and \"L\" to load.");
- }
- void SaveByte(byte[] byteArray, string key)
- {
- List<string> idList = new List<string>();
- XDocument doc = new XDocument();
- //Transforma cada elemento do byte[](array) em um elemento do XML
- doc.Add(new XElement("root", byteArray.Select(x => new XElement("item", x))));
- //Deixa todo o string em uma linha
- string xmlString = AllStringToOneLine(doc.ToString());
- //------------------------------------------------------
- //Número máximo de "char"/letra dentro de uma linha na string
- int LineLengthMax = 200000;
- //Calcula o número de quebra de linhas
- int NumberBreaklines = (xmlString.Length / LineLengthMax);
- //Debug.Log("NumberBreaklines: " + NumberBreaklines);
- //vamos pegar as posições onde vamos colocar a quebra de linha
- for (int i = 1; i <= NumberBreaklines; i++)
- {
- //Calcula onde a quebra de linha vai ser inserida
- int x = LineLengthMax * i;
- //Criamos quebras de linhas em várias posições da string.
- xmlString = xmlString.Insert(x, "\n");
- }
- //------------------------------------------------------
- //Transforma cada linha em um elemento da "List"
- idList = xmlString.Split(new[] { "\n" }, StringSplitOptions.None).ToList();
- //Salva Todos os elementos do List/Array
- for (int i = 0; i <= idList.ToArray().Length - 1; i++)
- {
- //Salva a informação em bytes(número) em formato de texto/XML;
- PlayerPrefs.SetString(key + i, idList[i]);
- }
- //Salva o número de elementos do List/Array
- PlayerPrefs.SetInt(key + "size", idList.ToArray().Length);
- Debug.Log("saved");
- }
- byte[] LoadBytes(string key)
- {
- byte[] byteArray;
- string loadedStr = "";
- //carrega o número de linhas
- int a = PlayerPrefs.GetInt(key + "size");
- for (int i = 0; i <= a - 1; i++)
- {
- //Carrega toda a informação em bytes(número) em formato de texto/XML
- loadedStr += PlayerPrefs.GetString(key + i);
- }
- //Transforma o texto em um documento XML
- XDocument doc = XDocument.Parse(loadedStr);
- // counts direct children of the root element
- //int childrenCount = doc.Root.Elements().Count();
- //Debug.Log("children Count: " + childrenCount);
- //=====================================================
- //Transforma cada elemento do XML em um elemnto para a "var array int"
- var array = doc.Descendants("item").Select(x => (int)x).ToArray();
- //Debug.Log("array index 0: " + array[0]);
- //Debug.Log("array last index: " + array[array.Length - 1]);
- //Debug.Log("var array size: " + array.Length);
- //=====================================================
- //Transforma cada elemento do "array int" em um elemnto para a "byte array"
- byteArray = array.Select(x => (byte)x).ToArray();
- //Debug.Log("byteArray size: " + byteArray.Length);
- //Debug.Log("byteArray index 0: " + byteArray[0]);
- //Debug.Log("byteArray last index: " + byteArray[byteArray.Length - 1]);
- Debug.Log("Loaded");
- return byteArray;
- }
- string AllStringToOneLine(string word)
- {
- string charRepalcedSpace = " ";
- // Remove os espaços em exesso;
- Regex rgx = new Regex("\\s+");
- // substitui multiplos espaços por um espaço
- return word = rgx.Replace(word, charRepalcedSpace);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement