Saving Data in Unity

Hal Brooks
2 min readJan 22, 2022

--

Objective: Save case information including an image to a file.

The Case class has several string variables and a byte array for storing an image. The Case class is System.Serializable so that it can be saved.

Case class.

The code below takes the picture using NativePicture, previously discussed, allowing the texture to be read using the false option. In addition the string imagePath records the path where the picture was saved. Images in Unity are rendered as textures, but are typically saved as byte arrays.

NativeCamera saves a picture at path.

When the next button is pressed on the Take_Photo_Panel the ProcessInfo() method converts the saved texture to a byte[] array, imageData, using the EncodeToPNG() method for Texture2D. This is then assigned to the UIManager’s activeCase photoTaken byte[] array.

ProcessInfo() method in TakePhotoPanel script.

The Case will be saved when the SubmitButton method in the UIManager, shown below, is called via its namesake’s On Click(). This method creates an awsCase is assigned the activeCase’s variables. This method requires two namespaces, using System.Runtime.Serialization.Formatters.Binary and using System.IO. The BinaryFormatter or bf allows creation of a file in the persistentDataPath for the device. The bf.Serialize writes the awsCase to this file. Finally, the file is closed. The Debug.Log shows the actual path in Unity’s console window. The data is now saved on the android device and can be accessed later.

SubmitButton() method in UIManager.

The OverviewPanel uses the UIManager’s activeCase data to reconstruct the texture from its photoTaken byte[] array. A 1 x 1 texture2D, rebuildImage, is created; however, its size is immaterial, as it will be reassigned to the texture loaded from the photoTaken byte[] array in the activeCase of the UIManager. The Overview Panel’s photoTaken.texture is assigned to the rebuildImage and displays the photo in the OverviewPanel.

OnEnable() in OverviewPanel script used to rebuild photo texture for display.

--

--

No responses yet