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
2
Question by Strangerweather · Mar 05, 2016 at 05:32 PM · script.gamejsonlinkquiz

Code to integrate Json database?

Hi guys

I have a Trivia Game which I made following a tutorial. In this tutorial, there is a list of 10 questions which are integrated within the main C# script. I intend to create hundreds of questions so I would like a separate database for my questions. I have transferred my questions to a Json file. The problem is that I don't know how to link my C# script to the Json file, so that questions are retrieved.

Here is the code from the tutorial:

     void Start () {
 
         
         for (int i = 0; i < questionNumbersChosen.Length; i++)
         {
             questionNumbersChosen[i] = -1;
         }
         questions[0] = new Question("question?", new string[] { "answer", "answer", "answer", "answer", "answer" }, 3);
 
         chooseQuestions();
         assignQuestion(questionNumbersChosen[0]);
     }

I tried changing the questions bit to:

 string filepath = Application.streamingAssetsPath;
         DirectoryInfo dir = new DirectoryInfo(filepath);
         FileInfo[] files = dir.GetFiles("*.json");

But this is not working to link my script and the database.

Any pointers would be welcome!

Thanks!

Comment
Add comment · Show 2
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 savlon · Mar 05, 2016 at 09:21 PM 1
Share

Use System.IO for File. Obtain the text from json file by using File.ReadAllText(path to json file plus name plus .json extension). Then use a json parser such as LitJson and concert the string to a JsonData object. Check the quick guide on LitJson website for a better tutorial :)

avatar image Strangerweather savlon · Mar 06, 2016 at 07:42 AM 0
Share

Thanks, that's really helpful. I'll give it a go! :)

2 Replies

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

Answer by savlon · Mar 06, 2016 at 08:31 PM

I will show you the method I use to obtain data from a Json file.

First you will need to download a Json parser. I personally have only used LitJson and this is what I'll show you how to use.

Drag the .dll file you downloaded into your Assets folder. It should automatically update your references, but if it doesn't then you'll need to follow the steps in the Using DLL tutorial that Unity has provided.

Next you will need to create a Json file. You can do this in any basic text editor by creating the file and saving it with the file ".json" file extension. Below I've provided you with an example.

 {
     "questions": [{
         "question": "How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
         "answers": [
             0,
             7,
             13,
             27
         ],
         "correct": 27
     }, {
         "question": "She sells sea shells by the sea shore, how many sea shells did she sell?",
         "answers": [
             1,
             2.2,
             27,
             "Who cares!"
         ],
         "correct": 27
     }]
 }

Note: Creating your own Json file with data inside of it can be confusing and you may miss minor errors, which will become a huge problem later when you try to obtain data from it. I would suggest you validate your json text every time you change something. You can validate your text here

You will need to save this json file with any name as long as the extension is .json. Make sure this file is somewhere in your Assets folder (You will need to know the path).

Now we create a simple class to load the string of the file and convert it to JsonData which is what you'll be working with.

 using UnityEngine;
 using System.Collections;
 using System.IO;
 using LitJson;
 
 public static class JsonLoader
 {
     public static JsonData LoadFile (string path)
     {
         var fileContents = File.ReadAllText (path);
         var data = JsonMapper.ToObject (fileContents);
         return data;
     }
 }

Note: There is no error checking in the above script for simplicity sake. You should implement it to avoid Where's Wally errors.

Now we'll create a basic class to demonstrate the data we can obtain using the above code.

 using UnityEngine;
 using System.Collections;
 using LitJson;
 
 public class QuestionLoader
 {
     public QuestionLoader()
     {
         // Load the Json file and store its contents in a 'JsonData' variable
         var data = JsonLoader.LoadFile (Application.dataPath + "/Resources/Questions.json");
         // Access the "questions" array in the file and store them in a questions variable (JsonData)
         var questions = data["questions"];
 
         // Loop through all of the contents in the questions variable
         for (int i = 0; i < questions.Count; i++)
         {
             // Obtain the current questions data
             var currentQuestionData = questions[i];
             // Obtain the actual question "How much wood would..."
             var question = currentQuestionData["question"];
             // Obtain the answers "0, 7, 13..."
             var answers = currentQuestionData["answers"];
             // Obtain the correct answer "27"
             var correct = currentQuestionData["correct"];
 
             // Print the contents to the Debug Console
             Debug.Log (string.Format ("Question: {0}\nAnswers: {1}, {2}, {3}, {4}\nCorrect: {5}",
                 question, answers[0], answers[1], answers[2], answers[3], correct));
         }
     }
 }

Once again, I have not added any error checking as it may be a little overwhelming as it is. I have commented the code for you so you may need to study the json file and the code to figure out what is happening.

From here you're on your own. I suggest you check out LitJson's Quickstart Guide for more information on loading and saving data.

Goodluck!

Edit: Here are the results of the above code

 Question: How much wood would a woodchuck chuck if a woodchuck could chuck wood?
 Answers: 0, 7, 13, 27
 Correct: 27
 Question: She sells sea shells by the sea shore, how many sea shells did she sell?
 Answers: 1, 2.2, 27, Who cares!
 Correct: 27
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 Strangerweather · Mar 06, 2016 at 10:01 PM 0
Share

Wow, thank you so much, that is very generous of you! I did spend most of the day trying to work this out. I managed the questions part but not the answers. So this is going to be great! :)

avatar image savlon · Mar 07, 2016 at 05:59 AM 1
Share

You're welcome. If your database of questions is going to be rather large, I would consider using naphier's method using Sql. As he states, you won't need to load the entire database into memory prior to viewing some of its contents. At the end of the day there are still uses for loading and saving to json file. :)

avatar image
1

Answer by Naphier · Mar 06, 2016 at 09:28 PM

http://docs.unity3d.com/Manual/JSONSerialization.html

Unity now has a built-in json serializer. It does not do dictionaries so you will need to implement your own ISerializationCallbackReceiver interface implementation in your json object class. For a dictionary, this amounts to two Lists per dictionary (one for the dictionary's keys and another for its values). There are examples of this for ScriptableObject serialization if you need it.

That said:

Editing json can be a pain. If you're transferring data to a server definitely use it, but if this is a local static database consider an easier format for a database. SQLite4Unity is nice. It also gives you the power of SQLite queries instead of having to load the entire database into classes/objects.

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 Strangerweather · Mar 06, 2016 at 10:03 PM 0
Share

Brilliant, I'll look into this too! What would be the advantage of having my database on a server? And thanks for the reply! :)

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

54 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

Related Questions

How to add images to answers within a quiz game? 0 Answers

How to make Match 3 versus game AI C#? 0 Answers

Randomizing numbers on a list. 4 Answers

How to check the result after playing in quiz game?[Solve] -1 Answers

Score no longer works after backing up my game 0 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