Unity3d Learning (ii): Storing and Reading object data using JSON

Source: Internet
Author: User
Tags event listener

Objective

Some time ago completed their own small game konster production, and today re-read the next code. The original storage of the level unlock data uses Unity's own playerpref (dictionary-stored data).

Code to read the level data:

voidAwake () {foreach(Transform ChildinchTransform//Update level Lists        {            //Get level ' s Name            stringLevelName = Child.name.Substring (0,1); //Load level data, check if it is unlocked            if(Playerprefs.getint (levelname) = =0)//Set Lock{child.getchild (1). Gameobject.setactive (true); }            Else{child.getchild (1). Gameobject.setactive (false); }        }    }

To unlock the next level when a customs clearance is cleared:

 Public voidLevelcompleted ()//Level completed    {        inttemp = Thislevel +1;//Next level        stringNextlevel =temp.        ToString (); if(Playerprefs.getint (nextlevel) = =0)//Check if Next level is lockedPlayerprefs.setint (Nextlevel,1);        Playerprefs.save ();  Startcoroutine (Gamesuccess ()); //Show the gamesuccess UI}

Personally, although it is convenient to use, but if I want to access some object structure data is very troublesome, so I tried to write a simple object data storage.

Storing data using JSON

What is JSON

JSON is a lightweight format for data interchange. The essence of it is actually a string of objects that are stored on a key-value basis.

For example, there is a person class:

 Public classperson{ Public stringname;  Public intAge ;  PublicPerson (string_name,int_age) {      //ConstructorName =_name; Age=_age; }}//Static voidMain () {person KK=NewPerson ("KK", -);}

Then instantiate a person named KK, then its JSON string format is: {"name": "KK", "Age": "19"}.

Application: Using JSON to store level data

Here is the Jsonfx, one based on. NET's JSON operations library. 1 (CSDN) 2 (GitHub)

First we need to determine the storage path for the next data, where a filepath class is defined to hold all paths (global variables).

 Public classfilepath{ Public Static ReadOnly stringGamedata_path = Application.datapath +"/gamedata";//folder for game data     Public Static ReadOnly stringLevel_path = Gamedata_path +"/leveldata.txt";//level unlock data store path
You can expand when new data is needed to store the path
}

Then simply encapsulate the JSON operation and file IO operations:

usingJsonfx.json;usingSystem.IO; Public classdatamanager{//Saving Object Data     Public Static voidSaveclass<t> (T Saveclass,stringpath) {       //if the game Data folder does not exist, create a folder        if(!directory.exists (Filepath.gamedata_path))        Directory.CreateDirectory (Filepath.gamedata_path);            File.writealltext (Path, jsonwriter.serialize (Saveclass)); }   //Reading Object Data     Public StaticT loadclass<t> (stringpath) {        stringList =file.readalltext (path); returnJsonreader.deserialize<t>(list); }}

Then you define a level class to hold individual levels of data, and it is important to note that JSON-serialized objects must explicitly indicate the default constructor, or Jsonfx will error.

 Public classlevel{//level number     Public intLevelnumber {Get;Set; } //whether the level is unlocked     Public BOOLisunlocked {Get;Set; }  PublicLevel () {}//you must provide a default constructor     PublicLevel (int_levelnumber,BOOL_isunlocked) {Levelnumber=_levelnumber; Isunlocked=_isunlocked; }}

Define a levellist to store all the levels.

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classlevellists{ PublicList<level>lists; //default constructor for JSON serialization and deserialization     Publiclevellists () {}/// <summary>    ///assignment constructor for initialization of the first launch of the game/// </summary>     PublicLevellists (intlevels) {Lists=NewList<level>(); Lists. ADD (NewLevel (1,true));//Level 1 must be unlocked in advance.         for(inti =2; I <= levels;i++) {lists. ADD (NewLevel (I,false));//remaining levels locked        }    }}

Then, in order to initialize the data at the first boot of the game, we need a script firstlaunch to detect if the game was first launched. Create an empty object in the scene and hang up the script.

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classFirstlaunch:monobehaviour { Public intInitlevelnum;//number of levels initialized, fill in the editor's inspector, I filled in 4 off    voidAwake () {Check (); }    voidCheck ()//Check if the game is the first time you start    {        intIsfirstlaunch = Playerprefs.getint (" First");//gets the value corresponding to this key, there is no default of 0        if(Isfirstlaunch = =0)         {            //If it does not exist, create and set the value to 1Playerprefs.setint (" First",1);            Playerprefs.save ();        Initializelevellists (); }    }    voidInitializelevellists ()//Initialize the data for the level list locally{levellists MyList=Newlevellists (Initlevelnum); Datamanager.saveclass<LevelLists>(MyList, Filepath.level_path); }}

Then for the level list, we write a script to manage its state

usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine;usingUnityengine.ui; Public classlevelscontroll:monobehaviour{ PublicGameobject[] levels;//Level Selection     PublicGameobject[] Locks;//level lock//Use this for initialization    voidStart () {Initialize (); }        voidInitialize ()//Level list Initialization    {        //reading level datalevellists data = datamanager.loadclass<levellists>(Filepath.level_path);  for(inti =0; I < levels.length;i++)        {            //Initialize Click event ListenerClicklistener.get (Levels[i]). OnClick + =Selectlevels; //Initialize level unlock statusLocks[i]. SetActive (!Data.lists[i].        isunlocked); }    }     Public voidselectlevels (Gameobject go) {inti =0;  for(; I < levels.length;i++)        {            if(Go = =Levels[i]) Break; }        //Load level here for the test directly printedDebug.Log ("Load Level"+ (i +1)); }}

Because the level selection is directly used by the Ugui image component, it does not have UI click event handling, but we can write a script ourselves to implement Unity's Click event interface Ipointerclickhandler to listen for click events.

usingUnityengine;usingUnityengine.eventsystems; Public classClicklistener:monobehaviour, Ipointerclickhandler//Note that this is the click interface provided by Unity{     Public Delegate voidVoiddelegate (Gameobject go);//Event Delegate     Publicvoiddelegate OnClick;  Public StaticClicklistener Get (Gameobject go)//get the listener script for the corresponding gameobject, without adding a new one{Clicklistener Listener= go. Getcomponent<clicklistener>(); if(Listener = =NULL) Listener= go. Addcomponent<clicklistener>(); returnListener; }     Public voidOnpointerclick (Pointereventdata eventData) {if(OnClick! =NULL) OnClick (gameobject); }}

OK, then fix the UI in the scene, hang up the script, and click Run.

You can find a folder called GameData, and then create a new Leveldata.txt file under the folder that stores the data for the level.

Stop running, and here I again in the text file in the Isunlocked property of the four to true, and then run, found that the four-off unlocked.

As a result, a simple level data store is complete.

Of course, there is no security, players only need to modify the text file in the corresponding folder can be unlocked, so sometimes we need to encrypt the data. About data encryption is another topic ( ̄▽ ̄).

Resources

The unity5.x Development Guide, the transcript of Rosa

Ugui Research Institute Control and Button monitoring Event System (v) Glaze Momo

Unity3d Learning (ii): Storing and Reading object data using JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.