JsonUtility how to break json into new line - c#

I been follow the tutorial from this video.
The tutorial source code can be found at here...
I have a problem of my Json data all been stored in 1 single line,
I want the data break into new line for single object data
Here the code for the Json tutorial
Actor file
using UnityEngine;
using System.Collections;
using System;
public class Actor : MonoBehaviour {
public ActorData data = new ActorData();
public string name = "Tile";
string newline = "\n";
public void StoreData()
{
data.name = name;
data.pos = transform.position;
}
public void LoadData()
{
name = data.name;
transform.position = data.pos;
}
public void ApplyData()
{
SaveData.AddActorData(data);
}
void OnEnable()
{
SaveData.OnLoaded += LoadData;
SaveData.OnBeforeSave += StoreData;
SaveData.OnBeforeSave += ApplyData;
}
void OnDisable()
{
SaveData.OnLoaded -= LoadData;
SaveData.OnBeforeSave -= StoreData;
SaveData.OnBeforeSave -= ApplyData;
}
}
[Serializable]
public class ActorData
{
public string name;
public Vector2 pos;
}
save data file
using UnityEngine;
using System.Collections;
using System.Xml.Serialization;
using System.IO;
public class SaveData
{
public static ActorContainer actorContainer = new ActorContainer();
public delegate void SerializeAction();
public static event SerializeAction OnLoaded;
public static event SerializeAction OnBeforeSave;
public static void Load(string path)
{
actorContainer = LoadActors(path);
foreach (ActorData data in actorContainer.actors)
{
GameController.CreateActor(data, GameController.playerPath,
data.pos, Quaternion.identity);
}
OnLoaded();
ClearActorList();
}
public static void Save(string path, ActorContainer actors)
{
OnBeforeSave();
//ClearSave(path);
SaveActors(path, actors);
ClearActorList();
}
public static void AddActorData(ActorData data)
{
actorContainer.actors.Add(data);
}
public static void ClearActorList()
{
actorContainer.actors.Clear();
}
private static ActorContainer LoadActors(string path)
{
string json = File.ReadAllText(path);
return JsonUtility.FromJson<ActorContainer>(json);
}
private static void SaveActors(string path, ActorContainer actors)
{
string json = JsonUtility.ToJson(actors);
StreamWriter sw = File.CreateText(path);
sw.Close();
File.WriteAllText(path, json);
}
}

There are two overloads for the JsonUtility.ToJson function:
public static string ToJson(object obj);
public static string ToJson(object obj, bool prettyPrint);
Use the second one and pass true to it. It will format the output for readability making the json separated into lines.
Just replace string json = JsonUtility.ToJson(actors); with string json = JsonUtility.ToJson(actors, true);
If you are not satisfied with the result, use Newtonsoft.Json for Unity and format the json like this:
string json = JsonConvert.SerializeObject(actors);
string newLineJson = JValue.Parse(json).ToString(Formatting.Indented);

Related

Loading Json File with Button Unity

I have been working on a customization system that allows a player to customize their skin color and particle trail of their character. I have the system working and am now attempting to save the data through JsonUtility and then load it. I plan on saving the data with the play button then transitioning to a new scene and having it load at start() of the new scene. But, for testing I have been using a load button as it should still work...but it doesn't.
My current SaveSystem script is supposedly working since the DebugLog "Save file created" for saving files appears when the button is pressed. But, when pressing the load button nothing changes yet the DebugLog "Save file found and loaded" still appears. I am kinda lost as to where to go and how to load the data into the Customization script since I am still new to C# Json and serializing in general.
Here are my 3 scripts:
SaveSystem Script
using UnityEngine;
using System.IO;
public static class SaveSystem
using UnityEngine;
using System.IO;
public static class SaveSystem
{
public static string directory = "/saveData";
public static string fileName = "MyData.txt";
public static void SavePlayer(Customization CurrentCustomization)
{
string dir = Application.persistentDataPath + directory;
if(!Directory.Exists(dir))
Directory.CreateDirectory(dir);
Debug.Log("Save file created");
string json = JsonUtility.ToJson(CurrentCustomization);
File.WriteAllText(dir + fileName, json);
}
public static Customization LoadPlayer()
{
string fullPath = Application.persistentDataPath + directory + fileName;
Customization CurrentCustomization = new Customization();
if(File.Exists(fullPath))
{
string json = File.ReadAllText(fullPath);
CurrentCustomization = JsonUtility.FromJson<Customization>(json);
Debug.Log("Save file found and loaded");
}
else
{
Debug.Log("Save file does not exist");
}
return CurrentCustomization;
}
}
CharacterCustomizaiton Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CharacterCustomization : MonoBehaviour
{
public List<Customization> Customizations;
public int currentCustomizationIndex;
public Customization CurrentCustomization {get; private set;}
[SerializeField] private TextMeshProUGUI bodyColorText;
[SerializeField] private TextMeshProUGUI trailText;
public void Save()
{
SaveSystem.SavePlayer(CurrentCustomization);
}
public void Load()
{
CurrentCustomization = SaveSystem.LoadPlayer();
}
void Awake()
{
foreach(var customization in Customizations)
{
customization.UpdateSubObjects();
customization.UpdateRenderers();
}
}
public void SelectBodyColor(bool isForward)
{
currentCustomizationIndex = 0;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextMaterial();
}
else
{
CurrentCustomization.PreviousMaterial();
}
bodyColorText.text = CurrentCustomization.materialIndex.ToString();
}
public void SelectLTrail(bool isForward)
{
currentCustomizationIndex = 1;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextSubObject();
}
else
{
CurrentCustomization.PreviousSubObject();
}
trailText.text = CurrentCustomization.subObjectIndex.ToString();
}
public void SelectRTrail(bool isForward)
{
currentCustomizationIndex = 2;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextSubObject();
}
else
{
CurrentCustomization.PreviousSubObject();
}
trailText.text = CurrentCustomization.subObjectIndex.ToString();
}
}
Customization Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Customization
{
public string DisplayName;
public List<Renderer> Renderers;
public List<Material> Materials;
public List<GameObject> SubObjects;
public int materialIndex;
public int subObjectIndex;
public void NextMaterial()
{
if(materialIndex == Materials.Count - 1)
{
materialIndex = 0;
}
else
{
materialIndex++;
}
UpdateRenderers();
}
public void PreviousMaterial()
{
if(materialIndex == 0)
{
materialIndex = Materials.Count - 1;
}
else
{
materialIndex--;
}
UpdateRenderers();
}
public void NextSubObject()
{
if(subObjectIndex == SubObjects.Count - 1)
{
subObjectIndex = 0;
}
else
{
subObjectIndex++;
}
UpdateSubObjects();
}
public void PreviousSubObject()
{
if(subObjectIndex == 0)
{
subObjectIndex = SubObjects.Count - 1;
}
else
{
subObjectIndex--;
}
UpdateSubObjects();
}
public void UpdateSubObjects()
{
for(var i = 0; i < SubObjects.Count; i++)
if (SubObjects[i])
SubObjects[i].SetActive(i == subObjectIndex);
}
public void UpdateRenderers()
{
foreach (var renderer in Renderers)
if (renderer)
renderer.material = Materials[materialIndex];
}
}

Get JSON data from Web in Unity

there is a problem that I haven't been able to solve for a few days.
im using this asset from assetstore (https://assetstore.unity.com/packages/tools/gui/enhancedscroller-36378)
For example, I have json data that looked like:
link : jsonplaceholder.typicode.com/todos/1
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
And i set up the data class like:
public class ScrollerData
{
public int userId;
public int id;
public string title;
public bool completed;
}
and my controller is like that :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using EnhancedUI.EnhancedScroller;
using UnityEngine.Networking;
public class ScrollerController : MonoBehaviour, IEnhancedScrollerDelegate
{
private List<ScrollerData> _data;
public EnhancedScroller myScroller;
public AnimalCellView animalCellViewPrefab;
public string _textURL;
void Start()
{
StartCoroutine(GetText());
_data = new List<ScrollerData>();
myScroller.Delegate = this;
myScroller.ReloadData();
}
public int GetNumberOfCells(EnhancedScroller scroller)
{
return _data.Count;
}
public float GetCellViewSize(EnhancedScroller scroller, int dataIndex)
{
return 300f;
}
private IEnumerator GetText()
{
using(UnityWebRequest request = UnityWebRequest.Get(_textURL))
{
yield return request.SendWebRequest();
if(request.isHttpError||request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
Debug.Log("Successfully downloaded text");
var text = request.downloadHandler.text;
ScrollerData catFact = JsonUtility.FromJson<ScrollerData>(text);
// _text.text = catFact.fact;
Debug.Log(text);
}
}
}
public EnhancedScrollerCellView GetCellView(EnhancedScroller scroller, int
dataIndex, int cellIndex)
{
AnimalCellView cellView = scroller.GetCellView(animalCellViewPrefab) as
AnimalCellView;
cellView.SetData(_data[dataIndex]);
return cellView;
}
}
and the cell view is like :
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using EnhancedUI.EnhancedScroller;
public class AnimalCellView : EnhancedScrollerCellView
{
public Text animalNameText;
public void SetData(ScrollerData data)
{
animalNameText.text = data.title;
}
}
my question is i want to use the json data in the controler in
public EnhancedScrollerCellView GetCellView(EnhancedScroller scroller, int
dataIndex, int cellIndex)
{
AnimalCellView cellView = scroller.GetCellView(animalCellViewPrefab) as
AnimalCellView;
cellView.SetData(_data[dataIndex]);
return cellView;
}
but because is couroutine i cant get data from json
anyone can help me

How to read data from a json file in unity2D

Hello I have a question on how I can read the data from a JSON file I have already made the saving method I just can't seem to find out how to read JSON files
Code for my saving system:
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GlobalControl : MonoBehaviour
{
public GameObject Player;
public void Save()
{
var player = Player.GetComponent<PlayerScript>();
PlayerData playerdata = new PlayerData();
playerdata.pos = player.transform.position;
playerdata.curreceny = player.currency;
playerdata.playerDebug = player.IsUsingDebug;
string json = JsonUtility.ToJson(playerdata);
Debug.Log("Player data has been saved");
File.WriteAllText(Application.dataPath + "playerData.json", json);
PlayerData loadedPlayerData = JsonUtility.FromJson<PlayerData>(json);
}
public class PlayerData
{
public bool playerDebug;
public Vector3 pos;
public int curreceny;
}
}
I happened to be implementing that on my application currently
i would suggest that you add this JSON file in StreamingAssets Folder inside your project
then access it
this is my function to read it
string filePath = Path.Combine(Application.streamingAssetsPath, jsonfileName);
WWW www = new WWW(filePath);
while (!www.isDone) { }
string dataAsJson = www.text;
OnRead(dataAsJson);
and this is the full class
using UnityEngine;
using System;
using System.IO;
using System.Threading.Tasks;
public class StreamingDataHandler
{
private static StreamingDataHandler Inistance
{
get
{
if (inistance == null) inistance = new StreamingDataHandler();
return inistance;
}
}
static StreamingDataHandler inistance;
private StreamingDataHandler()
{
}
public static void ReadStringFile(string jsonfileName, Action<string> OnRead, bool isAsync = true)
{
Inistance.ReadFile(jsonfileName, OnRead, isAsync);
}
private void ReadFile(string jsonfileName, Action<string> OnRead, bool isAsync = true)
{
string filePath = Path.Combine(Application.streamingAssetsPath, jsonfileName);
if (isAsync)
{
ReadStringFileAsync(filePath, OnRead);
}
else
{
string filePath = Path.Combine(Application.streamingAssetsPath, jsonfileName);
WWW www = new WWW(filePath);
while (!www.isDone) { }
string dataAsJson = www.text;
OnRead(dataAsJson);
}
}
private async void ReadStringFileAsync(string filePath, Action<string> OnRead)
{
WWW www = new WWW(filePath);
while (!www.isDone)
{
await Task.Yield();
}
string dataAsJson = www.text;
OnRead(dataAsJson);
}
}

Is using static classes in c# the same as procedural programming compiler-wise?

Basically I am using Unity and it used c#. I want to program procedurally. Can I mimick this with static namespaces and static classes, so that I can use the static namespaces as "header files", so I dont have to instantiate a bunch of singletons. How is this performance wise?
For example:
namespace Balls
{
public static Ball [] balls;
public static class Balls
{
public static void UpdateBalls (){}
}
}
Another file:
using static Balls;
namespace Player
{
public static class Player
{
public static bool PlayerAlive;
public static Vector3 position;
public static void UpdatePlayer ()
{
for (int i=0; i<balls.Length; i++)
{
if (position == balls[i].position)
{
PlayerAlive = false;
}
}
}
}
}
Another file:
using static Balls;
using static Player;
namespace Main
{
public static class Main
{
public static void MainUpdate ()
{
if (PlayerAlive)
{
UpdateBalls ();
UpdatePlayer ();
}
}
}
}

Saving ENUMs in C# and Loading it

Im trying to save some enums in my code. Saving and converting to the string is going well. But with the loading there r some problems. I mean. I just cant load it). Im doing all that in unity. I thought to convert enum to string and after convert it back. Conversion to string works fine. But what happens with back-convestion i dont know. Thanks.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameControl : MonoBehaviour {
public static GameControl control;
public float health;
public float experience;
public string stateString;
public enum State { start_0, start_1, start_3, start_4 };
public State myState;
void Awake () {
if(control == null)
{
DontDestroyOnLoad(gameObject);
control = this;
}
else if(control != this)
{
Destroy(gameObject);
}
}
public void Save()
{
stateString = myState.ToString(); //Converts ENUM to STRING
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath +
"/playerInfo.dat");
PlayerData data = new PlayerData();
data.health = health;
data.experience = experience;
data.stateString = stateString;
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
State loadedState = (State) Enum.Parse(typeof(State), stateString);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath +
"/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
health = data.health;
experience = data.experience;
stateString = data.stateString;
}
}
}
[Serializable]
class PlayerData
{
public float health;
public float experience;
public string stateString;
public enum State { start_0, start_1, start_3, start_4 };
public State myState;
}

Categories

Resources