Skip to content

Instantly share code, notes, and snippets.

@Demkeys
Last active October 17, 2018 02:42
Show Gist options
  • Save Demkeys/03a1945257d89f5cf822a61fa734c836 to your computer and use it in GitHub Desktop.
Save Demkeys/03a1945257d89f5cf822a61fa734c836 to your computer and use it in GitHub Desktop.
Example code for Unity, demonstrating how to pack a bool array into a string and unpack a string in a bool array.
/// <summary>
/// This script demonstrates how to convert a bool array to a string of bits and convert a string of bits to a bool array.
/// Usage:
/// - Attach this script to an empty gameobject. From the Inspector set the values of the items in the bool array.
/// - Enter Play Mode.
/// - Hit 'a' key, the values of the bool array will be converted to a bit string.
/// - Hit 's' key, bit string will be converted into a bool array.
/// </summary>
using UnityEngine;
public class BoolArrayToBitString : MonoBehaviour {
public bool[] boolValuesArr = { true, false, true, true, false };
string bitString = ""; // To store bits representing bool values
// Use this for initialization
void Start () {
}
// Read bool array and pack the data into a string.
void PackDataToBitString()
{
char[] bits = new char[boolValuesArr.Length];
for(int i = 0; i < bits.Length; i++)
{
bits[i] = boolValuesArr[i] == true ? '1' : '0';
}
bitString = new string(bits);
Debug.Log("Packed data: " + bitString);
}
// Read string and unpack the data into a bool array.
void UnpackDataFromBitString()
{
char[] bits = bitString.ToCharArray();
boolValuesArr = new bool[bits.Length];
for(int i = 0; i < bits.Length; i++)
{
boolValuesArr[i] = bits[i] == '1' ? true : false;
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.A)) { PackDataToBitString(); boolValuesArr = new bool[1]; }
else if (Input.GetKeyDown(KeyCode.S)) { UnpackDataFromBitString(); bitString = ""; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment