Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by dubiduboni_unity · Apr 12, 2019 at 10:39 AM · scripting problemscript.jsonfilewrite data

How can I save data to a text/json file and read it back and then assign the values back to the variables ?

The main goal is to be able to save and load the conversations List content to a file and read it back to the conversations List so it will be like it is now in the Inspector. The values should be assigned to the right variables and it should look like in the Inspector in the screenshot at the bottom.

I'm also not sure if I should use json or just simple text file and how to do it.

I have this script with a List type Conversation name conversations. I want to store the conversations to a file and to be able to read it back using two buttons for saving and for loading.

This is the script with the two methods for saving and loading :

 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using UnityEditor;
 using UnityEngine;
 
 [ExecuteInEditMode]
 public class DialogueTrigger : MonoBehaviour
 {
     public List<Conversation> conversations = new List<Conversation>();
 
     [HideInInspector]
     public int dialogueNum = 0;
 
     [HideInInspector]
     public int dialogueIndex = 0;
 
     private bool triggered = false;
     private List<Dialogue> oldDialogue;
     private bool activateButton = false;
 
     public void TriggerDialogue(int dialogueIndex)
     {
         this.dialogueIndex = dialogueIndex;
 
         if (conversations.Count > 0 &&
             conversations[dialogueIndex].Dialogues.Count > 0)
         {
             if (triggered == false)
             {
                 if (FindObjectOfType<DialogueManager>() != null)
                 {
                     FindObjectOfType<DialogueManager>().StartDialogue(conversations[dialogueIndex].Dialogues[dialogueNum]);
                     dialogueNum += 1;
                 }
                 triggered = true;
             }
         }
     }
 
     private void Update()
     {
         ButtonActivation();
 
         if (DialogueManager.dialogueEnded == true)
         {
             if (dialogueNum == conversations[dialogueIndex].Dialogues.Count)
             {
                 return;
             }
             else
             {
                 FindObjectOfType<DialogueManager>().StartDialogue(conversations[dialogueIndex].Dialogues[dialogueNum]);
                 DialogueManager.dialogueEnded = false;
                 dialogueNum += 1;
             }
         }
     }
 
     public bool ActivateButton()
     {
         return activateButton;
     }
 
     private void ButtonActivation()
     {
         if (ConversationsChecks() == true)
         {
             foreach (string sentence in conversations[dialogueIndex].Dialogues[dialogueNum].sentences)
             {
                 if (sentence != "")
                 {
                     activateButton = true;
                 }
                 else
                 {
                     activateButton = false;
                 }
             }
         }
         else
         {
             activateButton = false;
         }
     }
 
     public void SaveConversations()
     {
         string jsonTransform = JsonHelper.ToJson(conversations.ToArray(), true);
         File.WriteAllText(@"d:\json.txt", jsonTransform);
     }
 
     public void LoadConversations()
     {
         //string jsonTransform = File.ReadAllText(@"d:\json.txt");
         //conversations = JsonHelper.FromJson<Conversation>(jsonTransform);
         
     }
 
     private bool ConversationsChecks()
     {
         bool IsConversationsReady = false;
 
         if (conversations.Count > 0 &&
             conversations[dialogueIndex].Dialogues.Count > 0 &&
             conversations[dialogueIndex].Dialogues[dialogueNum].sentences.Count > 0 &&
             conversations[dialogueIndex].Dialogues[dialogueNum].name != "" &&
             conversations[dialogueIndex].name != "")
         {
             IsConversationsReady = true;
         }
         else
         {
             IsConversationsReady = false;
         }
 
         return IsConversationsReady;
     }
 }
 

This is the buttons script for now only for the saving :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEditor;
 using UnityEngine;
 
 [CustomEditor(typeof(DialogueTrigger))]
 public class SaveConversationsButton : Editor
 {
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
         
         DialogueTrigger dialoguetrigger = (DialogueTrigger)target;
 
         if(dialoguetrigger.ActivateButton() == true)
         {
             GUI.enabled = true;
         }
         else
         {
             GUI.enabled = false;
         }
         if (GUILayout.Button("Save Conversations"))
         {
             dialoguetrigger.SaveConversations();
         }
     }
 }
 

When I click the Save Conversations button it's writing the conversations List content to a file. This is how the file content looks like after saved:

 {
     "Items": [
         {
             "name": "Conversation 1",
             "Dialogues": [
                 {
                     "name": "Dialogue 1",
                     "sentences": [
                         "Hello World",
                         "It's my time to make a magic"
                     ]
                 }
             ]
         },
         {
             "name": "The openning scene",
             "Dialogues": [
                 {
                     "name": "NAVI",
                     "sentences": [
                         "Hello to you",
                         "Lets hide quick"
                     ]
                 },
                 {
                     "name": "PLAYER",
                     "sentences": [
                         "I'm the player now lets go"
                     ]
                 }
             ]
         }
     ]
 }


But now how do I read it back and assign it back to the conversation List ? So it will looks like as before in the Inspector ?

This is a screenshot of how it looks like in the Inspector :

Inspector

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Bunny83 · Apr 12, 2019 at 11:50 AM

All you need to do is this:

 public void LoadConversations()
 {
     string jsonTransform = File.ReadAllText(@"d:\json.txt");
     conversations = new List<Conversation>(JsonHelper.FromJson<Conversation>(jsonTransform));
 }

Alternatively without creating a new list you can do

 public void LoadConversations()
 {
     string jsonTransform = File.ReadAllText(@"d:\json.txt");
     conversations.Clear();
     conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
 }

Note when calling LoadConversations() from an editor script you may need to ensure to register a proper Undo action in order to actually get the changes serialized inside Unity. Though since you don't have a load button at the moment this code is generally missing in your script.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image dubiduboni_unity · Apr 12, 2019 at 12:10 PM 0
Share

Working great I added the Load button :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEditor;
 using UnityEngine;
 
 [CustomEditor(typeof(DialogueTrigger))]
 public class SaveConversationsButton : Editor
 {
     public override void OnInspectorGUI()
     {
         DrawDefaultInspector();
         
         DialogueTrigger dialoguetrigger = (DialogueTrigger)target;
 
         if(dialoguetrigger.ActivateButton() == true)
         {
             GUI.enabled = true;
         }
         else
         {
             GUI.enabled = false;
         }
         if (GUILayout.Button("Save Conversations"))
         {
             dialoguetrigger.SaveConversations();
         }
 
         GUI.enabled = true;
         if(GUILayout.Button("Load Conversations"))
         {
             dialoguetrigger.LoadConversations();
         }
     }
 }

And the trigger script in the load method :

 public void LoadConversations()
     {
         string jsonTransform = File.ReadAllText(@"d:\json.txt");
         conversations.Clear();
         conversations.AddRange(JsonHelper.FromJson<Conversation>(jsonTransform));
     }

Now how do I use and where to add the register a proper Undo action ?

avatar image Bunny83 dubiduboni_unity · Apr 12, 2019 at 12:16 PM 0
Share

Well it should probably just be:

 if(GUILayout.Button("Load Conversations"))
 {
     Undo.RecordObject(dialoguetrigger, "Loaded conversations from JSON");
     dialoguetrigger.LoadConversations();
 }
avatar image
1

Answer by Patel-Sagar · Apr 12, 2019 at 10:47 AM

Check this out if this fulfils your requirement. It is added by Unity.

https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity https://docs.unity3d.com/Manual/JSONSerialization.html

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Patel-Sagar · Apr 12, 2019 at 11:03 AM 0
Share

Let me know if it worked for you. @dubiduboni_unity

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

185 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Help, Reading a Json file (getting error KeyNotFounfExeption) 1 Answer

Why my Serializable class isn't receiving values from a Generic .json loader? 2 Answers

File.WriteAllText() on Android (Json file) 2 Answers

How can i convert float to int ? 0 Answers

Its not playing the Audio? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges