DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not...

65
DataKit - For Unity. www.unitygamesdevelopment.co.uk Created By Melli Georgiou © 2019 - 2020 Hell Tap Entertainment LTD The all-in-one solution for data serialization, save slots, save points and more.

Transcript of DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not...

Page 1: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKit-ForUnity.www.unitygamesdevelopment.co.uk

CreatedByMelliGeorgiou

©2019-2020HellTapEntertainmentLTD

Theall-in-onesolutionfordataserialization,saveslots,save

pointsandmore.

Page 2: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page2

Table of Contents

VersionHistory...................................................................................................................4Unity2019UpgradeNotes..............................................................................................5

DataKitV2UpgradeGuide..............................................................................................6

AnIntroductionToDataKit............................................................................................7WhatIsDataKit?..........................................................................................................................7WhatIsSerializationAndHowDoesItWorkInDataKit?.............................................8CompatibleDataTypes.............................................................................................................8WhyChooseDataKit?.............................................................................................................10WhatCanDataKitDoForYourProject?...........................................................................10

KeyConcepts....................................................................................................................12SaveSlots...................................................................................................................................12SavePoints................................................................................................................................12LocalData..................................................................................................................................12GlobalData................................................................................................................................12DataStorage.............................................................................................................................13ExternalAssets........................................................................................................................13

QuickSetup.......................................................................................................................14HowToSetupDataKit............................................................................................................14HowToSetupTheReferenceDatabase...........................................................................14HowToViewTheRuntimeDebugger...............................................................................14

AnOverviewOfDataKit................................................................................................15AboutThe‘DataKitSetup’Asset.........................................................................................15AboutThe‘ReferenceDatabase’Asset.............................................................................15AboutTheDebugger...............................................................................................................15AboutDataKitPreferences...................................................................................................16

SettingUpThe‘DataKitSetup’Asset........................................................................17TheLocalDataTab..................................................................................................................17TheGlobalDataTab................................................................................................................19TheOptionsTab.......................................................................................................................19TheEncryptionTab................................................................................................................23HowToStripEncryptionFromDataKit...........................................................................24

SettingUpThe'ReferenceDatabase'Asset............................................................25WhyCan'tISerializeReferencesLikeOtherValueTypes?.......................................25HowDoesTheDataKitReferenceDatabaseSolveThis?............................................25

Page 3: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page3

SettingUpYourReferences..................................................................................................26Requirements...........................................................................................................................27Considerations..........................................................................................................................27

SettingUpThe‘DataKitDebugger’............................................................................29LocalDataTab..........................................................................................................................29GlobalDataTab........................................................................................................................30SavePointsTab........................................................................................................................31

SettingUpTheDataKitPreferences.........................................................................34WorkingWithDataKit...................................................................................................35NeverMoveDataKitScripts.................................................................................................35WhereShallIStoreMyData?...............................................................................................35ShouldIWorryAboutDiskSpace?....................................................................................35DoINeedSaveSlots?..............................................................................................................36DoINeedSavePoints?...........................................................................................................36DoINeedToCaptureScreenshots?...................................................................................36HowDoIDifferentiateBetweenLocalAndGlobalData?...........................................37HowShouldISetupMyDataGroups?...............................................................................37HowShouldINameMyDataGroupsAndKeys?...........................................................37WhatTypeOfDataShouldISaveToMyKeys?..............................................................38ShallISaveLargeAssetsNormallyOrUseTheNewExternalAssetSystem?.....38TheRisksOfUsingCertainDataTypes............................................................................39

DataKitAPI........................................................................................................................40TimingIsEverything..............................................................................................................40PreloadingDataKitInTheEditor.......................................................................................40ExampleCode–TheBasics...................................................................................................41ExampleCode-OnInitialized..............................................................................................46ExampleCode–OnReadyandOnNotReady....................................................................48Events..........................................................................................................................................51CoreMethods............................................................................................................................52ScreenshotMethods................................................................................................................54FileManagementMethods....................................................................................................54GlobalDataMethods...............................................................................................................56LocalDataMethods.................................................................................................................59SaveFileMethods....................................................................................................................62SerializedDataMethods........................................................................................................63Import/ExportDataMethods............................................................................................64

Support...............................................................................................................................65

Page 4: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page4

Version History IMPORTANT:ALWAYSBACKUPYOURPROJECTSBEFOREUPDATING!DONOTUPGRADEDATAKITIFYOUHAVEALREADYRELEASEDYOURGAME!Pleasereadtheupgradeguideinthenextsectionformoreinformation.v2.1-FixesforUnity2019.3v2.0-Implemented"ExternalAssets".UserscannowsaveassetsintotheirownexternalfilestokeepDataKit'scoresavedatalightweightandblazinglyfast!-ReferenceDatabaseV2:allowssub-assets(children),automaticupdateswhencreatingbuilds,optionalinitializationmodesandsupportforTransforms(viaGameObjects).-NewMulti-threadingforloading,savinganddeletingexternalfiles.-inspectortypes:byte,short,decimal,AnimationCurve,Gradient,ShaderandTransform.-Newupdatedserializabletypesnowuseconstantstocachekeysresultinginmuchbetterperformance!-Save/LoadGlobalDataindependentlyintheEditor.-Debuggingoptionsforthreadsandexternalassets.-DataKit.IsReferenceDatabaseReady()APImethodtocheckwhethertheReferenceDatabaseisready.v1.0.1-DataKitnowhandlescorrupteddatafileswhenbuildingsavepointmaps.-Fixedpotentialmemoryleakwhenupdatingsavepointscreenshots.-FixedamemoryleakintheminiNotificationsUIinthedemoscenes.-FixedbugwithVector4'snotsavingtheWvaluecorrectly.

v1.0-FirstCommercialversionofplugin.

Page 5: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page5

Unity 2019 Upgrade Notes IMPORTANT:ALWAYSBACKUPYOURPROJECTSBEFOREUPDATING!

NOTE:Newuserscanskipthispage. TherearemajorchangesinUnity2019.xthataffecttheReferenceDatabase.

PrefabsHaveChanged(Unity2019.x)

ThewayprefabsworkinUnity2019havechanged.ThismeansanychildobjectsofprefabscannolongerbeindividuallyselectedintheReferenceDatabase.Ifyouwerepreviouslyreferencingprefabchildobjectsthisway,itwillnolongerwork.However,youshouldstillbeabletoreferencetheactualprefabitselfandotherchildobjects(suchassprites)shouldcontinuetoworknormallytoo.

AssetDatabaseV2(Unity2019.3)

ItisrecommendedthatifyouhavealreadyreleasedyourgameandyouneedtoupgradetoUnity2019.3,youshouldNOTupgradeyourAssetDatabasetoV2whenasked.ThisisbecausetheupgrademaychangeyouroriginalGUIDs.

Ifyourgamehasn'tbeenreleasedyet,thisshouldn'tbemuchofaproblem.AfterupgradingtoUnity'sAssetDatabaseV2,youwouldsimplyneedtoheadovertotheReferenceDatabaseandfindyourassetsagain(thismayaffectyourprevioussavepointsintheEditorbutnewsavepointsshouldbefine).

Page 6: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page6

DataKit V2 Upgrade Guide

IMPORTANT:DONOTUPGRADEFROMDATAKITv1.xIFYOUHAVEALREADYRELEASEDYOURGAME!DATAKITv2.0CANNOTREADSAVEDGAMEDATACREATEDWITHPREVIOUSVERSIONS.

NOTE:Newuserscanskipthispage.

Whathasbrokenbackwardscompatibility?

Thisupdaterequiredthescriptstobemovedfrom'Plugins'totherootdirectoryinordertomakeDataKitcompatiblewithuser-createdserializationsurrogates.

TheDataKitSetupassetshouldretainallofyourexistingkeysandsettingswiththeexceptionthatanyreferencesyousetasdefaultdatawillneedtobesetagain.

ThenewReferenceDatabaseandexistingscripts/APIsshouldbefine.

ItisimportantforusersnottomoveDataKit'sscriptstootherlocationsasthataffectshowserializationisperformed(andwillagainbreaksavegamedata).

Thisupgradeshouldnotbeattemptedforgamesthathavealreadybeenreleasedasitwillbeunabletoloadpreviouslysaveddata.Overthelongterm,thesechangeswillallowformorefeaturesandhelpDataKitmaximizecompatibility.

HowtoupgradefromDataKitv1.x:

First,youabsolutelymustbackupyourproject.Thiscannotbeoverstatedenough!Youshouldonlydothisifyourgamehasn'tbeenreleasedyet:

1)Createafoldernamed"HellTapEntertainment"attherootofyourproject.

2)Findthe"DataKit"folderlocatedat:

-Plugins/HellTapEntertainment/DataKitMoveittothenewHellTapEntertainmentfolder:

-HellTapEntertainment/DataKit3)InstalltheDataKitV2Packageandoverwriteallfiles.

DataKitshouldnowbeupgraded!

Page 7: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page7

An Introduction To DataKit

What Is DataKit? DataKitisauniquecross-platformdataserializationsystemtoautomaticallyhandlemostaspectsofsavingandloadingyourgame'sdata.Featuresincludelocalandglobaldata,saveslots,savepoints,datagroups,obfuscation,encryptionandevenautomaticscreenshots.AnothergreatDataKitfeatureistheintuitivevisualdebugger,allowingyoutoview,edit,deleteandrestoreyourserializeddatainreal-timewhiletestingyourgamesintheEditor!DataKitisapowerfulcoreassetthatanygameprojectwouldbenefitfrom!

Offeringuniqueandintuitivevisualeditors,youcaneasilysetupanddebugthedatayou’dliketosave.DataKitoffers“GlobalData”forstoringthingslikegraphicssettingsorIn-AppPurchasesand“LocalData”forsettingupwhatissavedineachsavepoint.Allofyourdatakeysareorganizedintogroupsforbettermanagementandfastperformance.

AlongwithoptionstosaveyourdatatolocalfilesordirectlyintoPlayerPrefs,youcanalsochoosehowmanysaveslotsandsavepointsyou’dlikeDataKittomanageforyou.Saveslotsallowyoutoimplementmultiplecharactersoraccounts.Savepointsareessentiallysnapshotsoflocaldata,allowingausertoloadthestateofthegameatapreviouspointintime.DataKitcanalsomanagedeletingtheoldestsavepointstokeepwithinamaximumlimit.

UnlikesystemssuchasPlayerPrefswhichonlysupportsavingintegers,floatsandstrings;DataKitallowsyoutoserializemostcommondatatypes,evenwhenusingarraysandcustomclasses(see'CompatibleTypes'forafulllist).DataKitalsooffersavarietyofwaystoserializereferences.TheoptionalReferenceDatabasesystemallowsyoutodirectlyreferencespecificassetslocatedintheResourcesfolder.Inaddition,manyreferences(textures,audio,meshes,etc.)canoptionallybesavedbyvalueratherthanreferenceinorderforthemtobecompletelyrecreatedondemand!

DataKitalsofeaturessomepowerfulobfuscationoptions!Youcandetercheatingbyobfuscatingyourdatawith128-bitAESEncryptionorwiththefasterbutless

Page 8: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page8

secureXORalgorithm.Ifyoudon’tneedencryption,DataKitcanliterallystripitoutofitsowncodebaseusingasimpleplatformdefineinUnity’PlayerSettings.

DataKitisdesignedtoworkinthebackgroundovermanyframes.Thismeansthefocusisonpreservingtheperformanceofyourgameratherthancausinghugehiccupswithfasterfileaccess.YoucanevenchoosetoslowdownDataKitinordertobalancegameperformance.ThisisespeciallygreatforplatformslikeVRandmobile!

Inshort,DataKitisapowerhouseofapluginthatwillgiveyounewandintuitivewaystosave,loadanddebugyourgame'sdata!

What Is Serialization And How Does It Work In DataKit? 'Serialization'istheprocessoftranslatinganobjectfrommemoryintoaformatthatcanbestored(inthiscase,takingdatafromyourgameandsavingittodisk).Theoppositeprocessofextractingthatdatafromaseriesofbytesisknownas'deserialization'.

DataKit'sinternalserializationsystemisbuiltontopofthestandard.net/monoBinaryFormatterclass.Thisisknowntobereliableandindustryproven.

DataKitextendsthebuilt-infunctionalityoftheBinaryFormatterclasstonativelysupportmostcommonlyusedUnitytypesthroughtheuseofcustom'Surrogates'(see'CompatibleDataTypes'belowforacompletelist).ItisalsopossibleforadvanceduserstoalsowritetheirownsurrogatesforDataKit,althoughthisshouldbeunnecessaryinmostcases.

Compatible Data Types ThefollowingDataTypesaresupportedinDataKit:

PrimitiveTypes:NOTE:Thesevaluetypescanbeserializeddirectly.

- int - float - string - byte - bool - char - long - short - uint - ulong - ushort - Enum - DateTime

Continued…

Page 9: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page9

Collections:NOTE:Collectionsthatcontaincollectionsarenotdirectlysupportedandshouldbeavoided.

- Arrays[] - 2DArrays[,] - 3DArrays[,,] - Dictionary<TKey,TValue> - List<T> - Queue<T> - HashTable<T> - HashSet<T> - Stack<T>

UnityValueTypes:NOTE:Thesevaluetypescanbeserializeddirectly.

- AnimationCurve - BoneWeight - Bounds - Color - Color32 - FrustrumPlanes - Keyframe - LayerMask - Matrix4x4 - Quaternion - Rect - Shader - Vector2 - Vector3 - Vector4

UnityReferenceTypes:NOTE:Youshouldtypicallyusethe'ReferenceDatabase'whenattemptingtoserializethesetypes:

- AnimationClip - Cubemap - Flare - Font - GameObject - GUISkin - SpriteAtlas - Tile - Transform - UnityEngine.Object

SpecialUnityReferenceTypes:

NOTE:Thesereferencetypeshavespecializedsurrogatesthatallowthemtoalsobesavedbyvalueaswellasreference(ifusingtheSaveLocalAsset/SaveGlobalAssetmethodsviatheAPI).Otherwise,youshouldtypicallyusethe'ReferenceDatabase'toserializethesetypes:

- AudioClip - Material - Mesh - PhysicMaterial - PhysicsMaterial2D - Sprite - Texture - Texture2D

Page 10: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page10

Why Choose DataKit? DataKithaspowerfulanduniquefeaturesthatsetitapartfromtraditionalSave-Gamesystemssuchas:

• Easytouse,visualeditorsforeverypartofthesystem.• DataKeysareorganizedinsideofDataGroups,allowingyoutobetter

organizeyourgamedataandinsomecases,speedupperformance.• TheDataKitDebuggerallowsyoutovisuallyview,edit,delete,revert,load

andsaveyourdatawhilethegameplaysintheEditor.• MostcommontypesofDatacanbeserialized(SeeCompatibleDataTypes)

andotherscanbeaddedviaSurrogates.• DirectlysavespecificreferencesviaDataKit’sReferenceDatabase.• SavespecificassetssuchasTextures,MeshesandAudioClipsbyvalue.• AutomaticallyhandleSaveSlots,SavePointsandScreenshotswithout

worryingaboutlowlevelfileoperations.• EasilycustomizeDataKitbychangingthenumberofsaveslots,save

points,screenshots,encryptionandmoreviathevisualeditors.• Setupthedefaultlocalandglobaldatayourgamewilluse.• DataKitallowsyoutorevertdatakeysandgroupsbacktodefaultvalues.• Extractserializeddatatosendandloadfromwebservers.• AnincrediblyrichandpowerfulAPI,nomatterifyou’resavingto

PlayerPrefsorLocalFiles.

What Can DataKit Do For Your Project?

• FEATURESDataKitgivesyouaninstantsolutionfordatastorageandmanagementwithahugeamountofbuilt-infunctionality.DataKitautomaticallyhandlesalllow-levelfileoperations,makingsuretopreparedirectoriesandfilesonauser’scomputertoactassaveslotsandsavepoints,deletingdata,etc.DataKitcanalsoautomaticallycapturescreenshotstobeusedasthumbnailsforyourSavePoints.Thisleavesyoufreetofocusontheimportantpartsofyourgame,likewhatdatayouactuallywanttosave,howthatdatashouldbeorganizedandhowmanySaveSlotsandSavePointsyouneed.NomatterhowyoucustomizeDataKitandwhichkindof

Page 11: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page11

storageyouuse,theunifiedAPIensuresyouinteractwithyourdatainthesameway.

• PERFORMANCEDataKitspreadsoperationsovertimewhichmeansitdoesn’tdumpallofitsprocessingintoasingleframeandcausemassivehiccups.Fileandsystemoperationsarebalancedtotryandmaintaingameperformanceasmuchaspossible.YoucanevenincreasethedelaybetweenfileoperationstoslowdownDataKitinordertobetterbalanceyourownprojects.

• EASEOFUSEDataKithasbeendesignedtosimplifytheprocessofsavingcomplexdatagroupsandkeysintoSaveSlotsandSavePoints.Allofthereallycomplicatedlow-levelstuffistakencareofforyou.Additionally,DataKitcanserializethemostcommondatatypes(aswellasUnity-specificdatatypes)soyoucansavethemalmostaseasyasyouwouldastringinUnity’sPlayerPrefssystem.Additionally,DataKitincludestheruntimedebuggertohelpyouseewhat’sgoingonwithyourdatainreal-time.

• CROSSPLATFORM&OPTIMIZEDYoumayhavenoticedthatDataKit’sdemosareavailableusingWebGLbuilds.We’vealsotestedandoptimizedfordesktopsandmobile!

• GREATSUPPORTAswellasthethoroughdocumentation,onlineforumandvideotutorials,friendlyemailsupportisalwaysathandifyouneedhelp!J

Page 12: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page12

Key Concepts

TobetterunderstandhowDataKitworks,it'sworthexplainingsomekeyconceptsbeforemovingfurther.

Save Slots SaveSlotsrepresentanabstractwayofseparatingsavedgamedata.Dependingonthetypeofgameyou'recreating,thiscouldbedifferentplayerprofilesonthesamedevice,differentcharacterswithinthesameaccount,etc.Youcouldalsothinkofthisintermsofusersonatypicalcomputer.DataKitcurrentlysupportsupto10SaveSlotspergame.

Save Points SavePointsareasnapshotofaplayer'sprogress;containingwhatistermedinDataKitjargonas"LocalData".AllSavePointsarelinkedtoitsassociatedSaveSlot.DataKitcurrentlysupportsupto100SavePointsperSaveSlot.

Local Data LocalDataistheactualinformationsavedineachSavePoint.LocalDataconsistsofacollectionofdatagroups,datakeys,screenshotthumbnails,andmetadata.

Global Data GlobalDataisdesignedtobetreatedindependentlyfromaparticularplayer'sprogress.ItisdistinctlyseparatefromSaveSlotsandSavePoints,makingitagreatwaytostoremorepersistentdatasuchasgraphicssettingsorIn-AppPurchases.Inotherwords,itisdatathatremainsthesameacrossanySaveSlotorSavePoint.

Page 13: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page13

Data Storage Bydefault,DataKitstoresyourgamedataasacollectionoflocalfilesinsideofafoldernamed"DataKit".You'llfindthisfolderlocatedinUnity'sApplication.persistentDataPath(whichisdifferentdependingonplatform).

ThefilesandfoldersinthisdirectoryareautomaticallyhandledbyDataKit.Youshouldneverattempttoadd,editordisruptthefilesandfolderswithinthisdirectoryasthiscaninterferewithDataKitandcauseerrors.Ifyouneedtovieworedityourgame'sdata,youshouldusetheDataKitDebuggerintheEditor.

ThescreenshotbelowshowsthefilestructureofDataKit'slocaldatafiles:

NOTE:YoucanalsochoosetostoreDataKit'sdatausing"PlayerPrefs"(forusewithplatformssuchasWebGL).Inthissetup,DataKitwillserializedatadirectlyusingPlayerPrefs.Thishassomedrawbacksandlimitationswhichyoucanreadaboutinthe'DesigningYourGame'sData'chapter.

External Assets StartingwithDataKitV2,usersmayopttosavelargeassetssuchastextures,meshes,andaudioclipsintoitsownexternalassetfileinordertokeepDataKit'sSavePointdatalightweightandblazinglyfast.ExternalAssetsareonlycompatiblewithDataKit's"LocalFiles"storagemode.

GlobalDataSaveSlots

SavePoints

SavePointData

ExternalAssets

Page 14: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page14

Quick Setup

AfterinstallingtheDataKitpackage,youcaneasilynavigatethesysteminthefollowingways:

How To Setup DataKit TosetupDataKitfromthemenu:GameObject>DataKit>DataKitSetup

TheDataKitSetupAssetwillnowbevisibleintheinspector.

How To Setup The Reference Database TosetuptheDataKitReferenceDatabasefromthemenu:GameObject>DataKit>DataKitReferenceDatabase

TheDataKitReferenceDatabaseAssetwillnowbevisibleintheinspector.

How To View The Runtime Debugger ToopentheRuntimeDebuggerfromthemenu:Window>DataKitDebugger

TheDataKitDebuggerwindowwillnowbevisible.

Page 15: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page15

An Overview Of DataKit

About The ‘DataKit Setup’ Asset

The“DataKitSetup”assetiswhereyoucansetuphowDataKitwillworkwithinyourproject.

Youcansetupyourdefaultlocalandglobaldata,SaveSlots,SavePoints,Screenshots,Encryptionandmore.

About The ‘Reference Database’ Asset

TheReferenceDatabaseisanoptionalsystemthatallowsyoutosetupspecificreferencestobedirectlyserializedanddeserializedinyourproject.

ThisrequiresyoutousetheResourcesfolderinorderforDataKittobeabletobuildadatabasethatlinkstheGUIDofthereferenceintheEditortotheruntimeversionoftheasset.

Moreinformationcanbefoundinthe‘ReferenceDatabase’section.

About The Debugger TheDataKitDebuggerallowsyoutoviewyourLocalandGlobalData,SaveSlotsandSavePointswhilethegamerunsintheEditor.

DataGroupsandKeyscanbeviewed,edited,deletedandrevertedbacktodefaultvalues.

YoucanalsosavenewSavePoints,loadexistingones,changebetweenSaveSlotsandmore.

Page 16: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page16

About DataKit Preferences

DataKithasitsownsectionintheUnityPreferenceswindow.

Youcansetuphowmuchinfoisdisplayedtoyouinthecustomeditorsaswellasabuttontoreverttodefaultsettings.

Page 17: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page17

Setting Up The ‘DataKit Setup’ Asset

The‘DataKitSetup’assetcustomizesDataKitforyourproject.Itallowsyoutosetupdefaultdata,SaveSlots,SavePoints,screenshots,encryptionandmore.Itconsistsofthe"LocalData","GlobalData","Options"and"Encryption"tabs.

The Local Data Tab

TheLocalDatataballowsyoutosetupthedefaultdatagroupsandkeysthatwillexistinaSavePointbydefault.It'sworthmentioningthatdatagroupsandkeyscanalsobeadded,edited,deletedandrevertedatruntime.

DefaultLocalDataGroup

Toaccesslocaldata,youwouldnormallyneedtotellDataKitwhatdatagroupandkeyyouwanttoaccessviatheAPI.

Asanexample,let’stakethefollowinglineofcodewhichtellsDataKittolookforagroupnamed“MyGroup”,findakeyinsideofitcalled“MyKey”andsetitto5.

DataKit.SetLocalKey( "MyGroup", "MyKey", 5 );

DataKitallowsyoutouseashortcuttoleaveoutthegroupnamebyusingthe‘defaultlocaldatagroup’field.Ifweweretosetthe‘defaultlocaldatagroup’fieldto"MyGroup",theshortenedcodebelowcouldbeusedinstead:

DataKit.SetLocalKey( "MyKey", 5 );

Page 18: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page18

Ifyouleaveoutthegroupname,DataKitwillautomaticallyusethe'defaultlocaldatagroup'fieldinitsplace.

Thisisusefulforsimplegamesthatonlyhaveasingledatagroup,allowingyoutosimplifyyourcodeforcommontasks.

LocalDataGroups

UnderneaththeDefaultGroupsection,youcancreate[+],remove[-]andre-arrange[↑/↓]DataGroupsusingthesmallbuttonsscatteredaroundtheUI.

DataGroupscanbeopenedandclosedusingthesmall"►" foldout icon in the top left of each group box.

WhenaDataGroupisopened,thefirstvisiblefieldisthe"GroupName",whichyoushouldusetogivethegroupauniquename.

QUICK-TIP:Avoidlonggroupandkeynamestokeepthesystemasfastaspossible.

ThenextthingtodoinyourDataGroupistosetupyourDataKeys.Thesekeyswillbestoringthedatayouwanttosave.Youcaneasilyadd[+],delete[-]andmove[↑/↓]datakeysusingthesmalliconsontherightoftheUI.

WhenyoucreateanewDataKey,youwillbeaskedtogiveitanameandaDataType.Bydefault,DataKeyswillbe'unassigned',meaningthateventhoughthekeyexists,ithasnoserializeddataandwillendupreturningadefaultvalueifausertriestoaccessit.

IfyouareusingaDataTypethatDataKitnativelysupports,itisrecommendedtosettheDataTypefromthedropdownmenu(forexample,aString)andsetacustomdefaultvalue.Ifyouwanttoserializeacustomclass,keeptheDataKeysetasunassigned(butbesuretosaveyourdatabeforetryingtoreadit).

Page 19: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page19

The Global Data Tab

TheGlobalDatatabisalmostidenticaltotheLocalDatatab.Thedifferenceisthedatasetupinthissectionwillbeusedasthedefault'GlobalData'availabletoallSaveSlotsandSavePoints.

The Options Tab

TheOptionstaballowsyoutosetupcoreDataKitfunctionalityandisdividedintoseveralsections.

StorageMode

YoucanchooseforDataKittosaveyourdatadirectlyto'LocalFiles'orviaUnity's'PlayerPrefs'system.BothmodesofferexactlythesameAPIsothereisnothingnewtolearn.However,therearesomedifferencestobeawareof:

SavingtoLocalFilesisthefastestmethodandallowsyoutoexceedthe1MBPlayerPrefslimitationonallsaveddata(although,itisrecommendedtokeepyourdiskusagebelow100KBperSavePointtokeepdiskI/Operformancesmoothacrossthemajorityofdevices).

PlayerPrefsmaybetheonlysolutiononsomeplatforms(suchasWebGL).DataKit'sPlayerPrefsmodeshouldbeequallyascrossplatformasUnity'sbuilt-inPlayerPrefssystem.Inthissetup,allsaveslotsandsavepointswillbesaved

Page 20: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page20

intothesame1MBPlayerPrefsfile.IfyouareusingmultipleSaveSlotsandSavePoints,thismeansyouwillneedtokeepaneyeonhowmuchdataissaved.

SaveSlots

SaveSlotsallowyoutoseparateandsaveLocalDataintodifferentaccounts(or'Slots').ThiscouldbeusedfordifferentcharactersinanRPG,differentuseraccounts,etc.

UseSaveSlotsShouldDataKitusemultipleSaveSlots?PleasenotethatifSaveSlotsaredisabled,DataKitwillinternallyuseasingleSaveSlot.

MaximumSaveSlotsHowManySaveSlotsShouldBeAllowed?DataKitcurrentlysupportsupto10SaveSlots.

SavePoints

YoucanautomaticallycreateSavePoints(asnapshotofLocalData)everytimeausersavesthegame.IfSaveSlotsareenabled,SavePointsareautomaticallysavedintothecurrentSaveSlot.

UseSavePointsShouldDataKituseSavePoints?PleasenotethatifSavePointsaredisabled,DataKitwillinternallyuseasingleSavePoint.

AutoReplaceOldSavePointsIfauserhasreachedthemaximumnumberofsavepoints,youcanenablethistoautomaticallydeletetheoldestsavepointtomakeroomfornewones.Thissavesyoufromhavingtomanuallycodetheprocessyourself.

MaximumSavePointsHowManySavePointsShouldBeAllowed?DataKitcurrentlysupportsupto100SavePointsineachSaveSlot.

InitializationOptions

ChoosethedefaultbehaviorofloadingdatawhenDataKitinitializes:

LoadGlobalAndDefaultLocalDataDataKitattemptstoloadanysavedGlobalDataandcreatesacopyofthedefaultlocaldata.Thisisthedefaultbehaviorrecommendedforbuilds.

LoadGlobalDataAndLatestSavePointDataKitattemptstoloadanysavedGlobalDataandthentriestoloadthelatestSavePointfromtheSaveSlotdefinedinthe"LoadFromSaveSlot"field.ThisworksparticularlywellwhendebuggingyourgamesintheEditor.

Page 21: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page21

Groups&Keys

Whensavingdata,groupsandkeyswillautomaticallybecreatedifitdoesn'talreadyexist.ThismimicsPlayerPrefs-likebehaviourbutaddsasmallamountofoverhead.Ifdisabled,keyswillnotbesavedunlessbothitsgroupandkeyiscreatedfirst.

AutoCreateGroups&KeysShouldPlayerPrefs-likefunctionalitybeusedinDataKit?Werecommendyouenablethisoption.

Auto-SaveDescriptions

WhenAuto-SavesaretriggeredthroughtheAPI,thedefaultsavepointdescriptionstringsbelowwillbeused:

Auto-SavePrefixThisstringisaddedbeforethesavedescription.

Auto-SavePostfixThisstringisaddedafterthesavedescription.

Screenshots

Ifthe'AutoCaptureScreenshots'optionisenabled,alow-resscreenshotisautomaticallycapturedwitheverySavePoint(youcanusethisasanicon/thumbnailinyourownSave/LoadUI).Theimagesizeandqualitycanalsobetweaked.Finally,adefaultscreenshotissetupforsituationswhereaSavePointdoesn'thaveitsown(orhasbeencorrupted).

AutoCaptureScreenshotsEverytimethegameissaved,ascreenshotisautomaticallycapturedandaddedtotheSavePoint.

ScreenshotSizeThesizeofthescreenshottosave.Largersizesincreasediskspace.

ScreenshotQualityThequalityofthescreenshottosave.Higherqualityincreasesdiskspace.

DefaultScreenshotATexture2DtobeusedwhenaSavePointdoesn'thaveasavedscreenshot.

Performance

DataKit'sfileoperationscanbesloweddowntohelpyoubalanceperformancehiccups.ThiscanbeespeciallyusefulonplatformslikemobileandVR.

AsyncDelayHowmanyextraframestoaddbetweenDataKitoperationstoslowdownthesystem.

SmootherDataCachingSlowdowncachingdatasizeswhileDataKitloadsyourdatatoattainsmootherperformance.

Page 22: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page22

SmootherReferenceResolversSlowdowntheinitializationofReferenceResolverssoitworkssimilartoDataKitv1.x.Ourtestingshowsthatthenewversionworksbetterbutfeelfreetochoosebetweenthetwo.

DebugOptions

Youcantogglethe"DataKitPreloading"featureintheEditoraswellasshowdebugmessagesforvariousDataKitsystems.Thefollowingoptionsareavailable:

PreloadDataKitInEditorWhenyoupressPlayintheEditor,DataKitwillrememberthesceneyouareworkingon,movetoaspecialpreloadersceneandinitializeitself.WhenDataKitisready,itwillautomaticallynavigatebacktotheoriginalsceneasnormal.ThisensuresthatDataKitisinan'initialized'statewhenyourscenebegins.Thisfeatureworksparticularlywellwiththe'LoadGlobalDataAndLatestSavePoint'InitializationOptionwhiletestingyourgamesinUnity.

DebugSavingShowconsolemessagestodowithsavingdata.

DebugLoadingShowconsolemessagestodowithloadingdata.

DebugDeletionShowconsolemessagestodowithdeletingdata.

DebugThreadsShowconsolemessagestodowithmulti-threading.

DebugSavePointMapsShowconsolemessagestodowithDataKit'sinternalsavepointmap.

DebugExternalAssetsShowconsolemessagestodowithExternalAssets.

Page 23: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page23

The Encryption Tab UsetheEncryptiontabtoconfigureDataKit'sbuilt-inEncryption/Obfuscationoptions.Itisveryimportanttounderstandthatwheneveryoumakeachangetothesesettingsallofyourexistingsaveddatawilllikelybreak.Therefore,nevermakechangestoEncryptionafteryourgameisreleased.

IMPORTANT:Pleasenotethatlocalencryptionisnot100%secure.UnlessthereisagoodreasontoenablelocalEncryption/Obfuscation,werecommendleavingitdisabled.

LockEncryptionSettings

Thishandycheckboxallowsyoutodisablealltheotherencryptionoptionstohelpprotectyourcurrentencryptionsettings.

EncryptionOptions

Ifencryptingdataisn'tnecessary,youshoulddisableEncryptionforthefastestperformance.Ifyouwouldliketosimplyobfuscatedatafromusers,XORisaveryfastchoice.ForthehighestleveloflocalEncryption,chooseAES.

UseEncryptionShouldencryption/obfuscationbeusedinDataKit?

EncryptionTypeYoucanchoosebetween128-bitAESlocalencryptionorXORobfuscation.

XORObfuscation

IfXORObfuscationisselected,noadditionalsetupisrequired.

Page 24: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page24

AESEncryption

IfAESEncryptionisselected,youmustuseanencryptionkeyaspartofthealgorithm.

Itissaferfornewusers(butlesssecure)touseDataKit'sdefaultAESkeyasithelpstoavoidthepossibilityofbreakingyourgameifyouloseyourcustomkey.

Ifyouaccepttherisksinvolvedwithprotectingyourownkey,youshouldclickthe"GenerateNewKey"buttontorandomizeanewAESkeytouse.

AESPassword

IfAESEncryptionisselected,youmustalsouseanencryptionpasswordtobeusedasadatavalidator.

JustliketheAESKey,itissaferfornewusers(butlesssecure)touseDataKit'sdefaultAESpasswordforthesamereason.

Ifyouaccepttherisksinvolvedwithprotectingyourownkeys,youshouldclickthe"GenerateNewPassword"buttontorandomizeanewAESpasswordtouse(oryoucansimplytypeyourownphrase).

BackingUp/RestoringYourCustomAESKeysandPassword

Ifyou'vechosentousenew/randomizedAESkeysandpasswords,youshouldswitchtheUnityEditorto'DebugMode'soyoucancopythestringsandmakeabackupofitelsewhere.Youcanrestorethisdatathesamewayifyouneedto.

How To Strip Encryption From DataKit Ifyou'vechosennottouseencryption/obfuscationandwishtocompletelystripallreferencesofitoutofthecode,youcandoiteasilybyaddingascriptingdefinesymbolcalled'DATAKIT_ENCRYPTION_OFF'inUnity'sPlayerSettings.

Page 25: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page25

Setting Up The 'Reference Database' Asset

TheDataKitReferenceDatabaseisanoptionalsystemthatallowsyoutodirectlyserializespecificreferencesinyourgamebyplacingthemina'Resources'folder.YoucanalternativelyusetheSaveLocalAssetandSaveGlobalAssetmethodstosaveanycompatiblereferencetypebyvalueviatheAPI.

Why Can't I Serialize References Like Other Value Types? SerializingreferencesisnotoriouslydifficultinUnity;mainlybecauseofthewayUnityhandlesassetsinruntimebuilds.WithintheUnityEditor,referenceshaveaGUIDwhichisusedasapersistentanduniqueidentifier.TheproblemisUnityremovestheseGUIDreferencesfromyourgameafteryoubuildit.

Anotherwaytoreferenceobjectsistouseits'InstanceID'.Theproblemwiththatisit'sunreliableasitoftenchangeseverytimeyoubuild/updateyourgame(aswellaseverytimeyourestartyourgame).Inotherwords,InstanceID'sarenotreliableastheprimarymethodtopointtoreferences.

How Does The DataKit Reference Database Solve This? Foruserswhoneeddirectaccesstoreferences,DataKitoffersawayaroundthisviatheResourcesFolder.Evenifnotideal,itisareliablewaytolocateareferenceacrossallplatformsbecauseitusessomethingpersistent–it'sfilepath.DataKitcanbuildadatabaseofreferencesalongwiththeiroriginalGUIDsandfilepathsintheResourcesfolder.Thisallowsittobeloadedondemandbehindthescenes.

Page 26: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page26

Fromascriptingperspective,thisallowsyoutotreatthesereferencesinalmostthesamewayasnormalvaluetypesandDataKitwillhandlethecomplextasksofresolvingthereferenceswhenyouneedthem.

IfyouchoosetousetheReferenceDatabase,DataKitneedstotemporarilyloadandre-linkeachofyourchosenassetsatthestartofthegame(whichcantakeafewmomentsdependingonthenumberofreferencesyou'reusing).

Thisisalsowhyasplashscreenisrecommendedinthiscase.Naturally,asplashscenedemoisalreadyprovidedintheDemosfolderandgoodtogo!

Setting Up Your References TheReferenceDatabaseeditorallowsyoutotellDataKitwhichreferencesyoudirectlywanttoaccess.YoudothisbyaddingassetsfromyourprojecttotheReferencedatabase.

ThetopareaoftheReferenceDatabaseallowsyoutoselectatabfromarangeofsupportedReferenceTypes(iftheoneyouwantisn'tlisted,usetheUnityEngine.Objecttype).

Underneaththetabsarethedropzones.DependingontheReferenceTypeyou'vechosen,youcandraganddropacompatiblefileofthattypeintothisareaforittoappearinthefilelistbelow.Notethattheleftdropzonewillreferencetheobjectaswellasallofitsvalidchildren,andtherightdropzonewillonlyreferencethespecificobjectyou'vedropped.

Page 27: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page27

Asyouadditemstothelist,you'llnoticethempopulatedwithinformationabouttheirvariousidentifiers.Youcanre-orderthelistwiththe[↑/↓]buttonsorremoveafilewiththe[-]button.

AtthebottomoftheReferenceDatabasearesomecommonbuttons:

Remove<Type>RemovesallassetsinthefilelistaboveforthechosenReferenceType.

FindAll<Type>AutomaticallyscansyourprojectforallcompatibleobjectsofthechosenReferenceTypeandaddsittothefilelist.

RemoveAllReferencesCompletelyremovesallreferencesfromallfilelistsintheReferenceDatabase.

FindAllReferencesAutomaticallyscansyourprojectforallcompatibleobjectsandaddsittoallfilelists.

Requirements CompatibleObjects

TheReferenceDatabasecanonlyuseassetfilesinyourResourcesfolderthatinheritfrom'UnityEngine.Object'(suchasTexture2D,AudioClip,Mesh,etc.).

StartingfromDataKitV2,evenvalidchildrenofassetsinyourResourcesfoldercannowbeaddedtotheReferenceDatabase!

ResourcesLimit

Unity'sResourcessystemcan'texceed2GB.YoushouldNOTsimplydumpallofyourreferencesinaResourcesfolder.

UniqueFilePathsInResources

Youshouldnothavemultipleobjectswiththesamefilepath.Anexampleofthisisifyouhave2'Resources'folderswithafilenamed"MyFile"residinginbothofthem.ThiswillconfuseUnity'sResourcessystemasbothfilepathswouldappeartobeidentical.Tofixthisyouwillneedtochangethenameofoneofthefiles.Thegoodnewsistheeditorwillshowwarningsifitdetectsthiskindofproblem.

Considerations GOLDENRULE:UseItIfYouNeedIt

Ifthere’sawaytosaveyourdatawithoutreferences,alwaysdoitthatway.

Page 28: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page28

BeSelective

EventhoughyoucanautomaticallyaddallcompatibleobjectsintotheReferenceDatabasewithasimpleclick,itisrecommendedtobeselective.Youshouldonlyaddtheobjectsyouactuallyneedtoreferencedirectly.

UpdateTheDatabaseAfterMovingFilesAround

Ifyou'vemovedsomeofyourfilesaroundorre-organizedyourResourcesfolders,youshouldmakesuretoclickbackintotheReferenceDatabase.Itwillautomaticallyupdatefilepathsifitdetectschanges.

Page 29: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page29

Setting Up The ‘DataKit Debugger’

The‘DataKitDebugger’windowallowsyoutodebugyourdatawhileitisrunningintheEditor.Itoffersanintuitivevisualapproachtodataandfilemanagement.Itconsistsofthe"LocalData","GlobalData"and"SavePoints"tabs.

Local Data Tab

The"LocalData"tabinthe'DataKitDebugger'isverysimilartothe"LocalData"tabfoundinthe'DataKitSetup'asset.IntheDataKitdebugger,thetabrepresentsthelivelocaldatacurrentlyloadedinmemoryratherthanthedefaultdatasetupofyourgame.Thereareseveraladditionaldifferences:

DataHeader

Theheaderareadisplaysusefulinformationaboutthecurrentdata.

ItwilltelluswhichversionofDataKitwasusedtocreateit,whatversionofyourowngamewasused,whichplatformitwassavedon,aswellasthetimestampandestimatedfilesize(thisisvisibleifdatawasloadedfromdisk).

Page 30: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page30

RealtimeSerialization

Realtimeserializationinaninspectorcanbequiteperformancehungry.Forthisreason,DataKitonlyshowsyouthecachedkeynamesandtypetokeepthingsblazinglyfast.Ifyouwanttodebugaspecifickey,youcanclickthe[→]buttontoenablereal-timeserialization.

Whenyoudothis,theDataKeywillbecomeeditable,allowingyoutoedititinthesamewayasyoucouldinthe'DataKitSetup'asset.

Whenyou'refinishedviewingoreditingadatakey,youcanclickthe[→]buttonagaintodisablereal-timeserialization.

RestoreData

DataKitalsooffersaverycoolfeaturethatallowsyoutorestoreadatakeyorgroupbypressingtherestore[↻]button.

PressingthisbuttononaDataKeywillattempttofindthedefaultvalueyousetintheDataKitSetupassetandrestoreit.IftheKeydidn'toriginallyexist,thisactionwillbeignored.

PressingthisbuttononaDataGroupwillattempttorestoretheentiregroupbacktoitsdefaultsettings.Thiswilldeleteanynewkeysyoucreatedsobecarefulwhenusingtheseactions.However,itisagreatwaytoeasilyrestoreyourDataGroupsbacktowhatyoucreatedinthe'DataKitSetup'asset.

TheseactionsarealsoavailableatruntimethroughDataKit'sAPI!

NOTE:IfyouarerevertingadatakeythatisconnectedtoanExternalAsset,theExternalAssetwillautomaticallybedeleted.

Global Data Tab

The"GlobalData"tabworksexactlythesamewayasthe"LocalData"tabbutrepresentsthecurrentglobaldatabeingusedinmemory.

Page 31: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page31

Save Points Tab

TheSavePointsTabisyourall-in-oneDataKitFileManagerbuiltrightintotheUnityEditor.

The"SavePoints"tabisseparatedintothefollowingareas:

Header

TheSaveSlotstabheadergivesusaquickoverviewofourdata.

IttellsuswhichDataKitversionweareusing,whatstoragetypeisbeingusedandwhatSaveSlotiscurrentlyselected.

SaveSlotSelection

TheareaundertheheaderallowsustoselectwhichSaveSlottouse(anddisplayswhichoneiscurrentlyin-use).

DependingonthemaximumnumberofSaveSlotsyouselectedintheDataKitSetupasset,aseriesofbuttonsrepresentingeachoftheavailableSaveSlotswillbevisible.ClickingontooneofthosebuttonswillchangetoanewSaveSlotandcauseDataKittoupdatealloftheassociatedSavePoints.

SavePointList

Underthe'SaveSlots'sectionisalistoftheavailableSavePoints.ItisimportanttorememberthateachoftheseSavePointsarelinkedandonlyavailabletothechosenSaveSlot.

Page 32: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page32

TheSavePointlistsarealwaysorderedbytimestamp(evenwhenusingtheAPI)withthenewestsavepointsatthetop.

Athumbnail,description,timestampandfilesizeoftheSavePointisdisplayedontheleft.OntherightisaLoad[↑]buttonwhichloadstheSavePointintomemoryandaRemove[-]buttonthatdeletestheSavePointfromdisk.

CreateSavePoint

ThenextareaallowsyoutocreateanewSavePointdirectlyintheEditor.

ThissimpleinterfaceallowsyoutogivethecurrentlocaldataadescriptionandusethesavebuttonontherighttocreateanewSavePoint.ThecurrentlocaldatawillbesavedtodiskandappearintheSavePointlist.

NOTE:WhensavinganewSavePoint,GlobalDataisalsoautomaticallysaved.

AdvancedActions

Finally,someadvancedactionbuttonsareavailable:

RevertLocalDataCompletelyrevertsallcurrentlocaldatabacktodefaultvalues.

RevertGlobalDataCompletelyrevertsallcurrentglobaldatabacktodefaultvalues.

RevertAllDataCompletelyrevertsallcurrentlocalandglobaldatabacktodefaultvalues.

SaveGlobalDataOnlySavesGlobalDatatodisk,ignoringanylocaldata.

LoadGlobalDataOnlyLoadsGlobalDatafromdisk,ignoringanylocaldata.

Page 33: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page33

DeleteSaveSlotXDeletesALLSavePointsinthecurrentSaveSlot.IMPORTANT:thiswillpermanentlydeleteyoursaveslotsandcannotbeundone.

DeleteAllSaveSlotsDeletesALLSavePointsinALLSaveSlots.IMPORTANT:thiswillpermanentlydeleteallofyoursavedgamedata.

Page 34: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page34

Setting Up The DataKit Preferences

TheDataKitPreferencespaneallowsyoutocustomizehowtheDataKiteditorsarepresentedtoyou.Thefollowingsettingsareavailable:

DataKitEditorSettingsShowDataKitHeadersThistogglestheiconandinfoatthetopoftheDataKitEditors.ShowTabHeadersThistogglestheiconandinfounderneathtabsintheDataKitEditors.ShowCodeSnippetsThistoggleshelpfulcodesnippetsthatallowyoutocopyandpastecommoncodeacrosstheDataKitEditors.

ResetDefaultSettings

ResetDataKitPreferencesButtonPushingthisbuttonallowsyoutoreverttheDataKitPreferencestothedefaultsettings.

Page 35: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page35

Working With DataKit ItisworththinkingabouthowyourgamedatashouldbedesignedtogetthemostoutofDataKit,aswellassomeotherhelpfultopics:

Never Move DataKit Scripts DataKit'sscriptsmustremainintheirdefaultlocations.TryingtomoveDataKittothepluginsfolderorelsewherewillcauseachangeinhowdataissavedandmakeyourpreviousgamedataunreadableaswellaspotentiallybreakcorefunctionality.

Where Shall I Store My Data? DataKitallowsyoutostoreyourdatadirectlyintolocalfiles(default)orviaUnity'sPlayerPrefssystem.Unlessyouneedtouseaplatformthatdoesn'tallowaccesstolocalfiles(suchasWebGL),itisrecommendedtoalwaysuse'LocalFiles'astheyarebestforperformanceandgivesyouwaymorestorage.

Thereisnohardlimitonthesizeoflocalfiles(otherthanauser'sharddiskspaceandlimitationsoftheOS/Filesystem)buthavinglargedatafilesmaycausehiccupsinperformancewhenperformingfileoperations.Forthisreason,werecommendaimingfornomorethan100kperSavePoint(butthelowerthebetter),especiallyforplatformslikeVRwhereperformancehiccupsshouldbeavoidedasmuchaspossible.

Toclarify,thisisnotalimitationbutratherarecommendationofgoodpractice.Ifyouabsolutelyneedmorediskspaceandyou'renotbuildingforVR,largerSavePointsshouldbefine.

Should I Worry About Disk Space? Thereisnohardlimitondiskspacewhenusing'LocalFiles'butasstatedintheprevioussection,youshouldcarefullyconsidertheamountofdatabeingsaved.

Ifyou'reusingPlayerPrefs,diskspacecanbecomeaconcernasUnityenforcesahardlimitof1MBonallofyourdata.IfyouwanttouseallSaveSlots(10)andallSavePoints(100),acrudeestimationwouldlooklikesomethingthis:

1024K/(10saveslots*100SavePoints)=1.024Kmaxstoragepersavepoint

Youcanseethatinthisscenario,itwouldmakeabsolutelynosensetosplityour1MBdatalimitacrossthismanysaveslotsandsavepointsastheuserwillbeleftwithslightlyover1KBpersavepoint(althoughitwilllikelybemuchlessduetooverhead).Thisalsodoesn’taccountforhowmuchdataisusedinGlobalData.Inotherwords,ifyouareusingPlayerPrefs,youmustbesensibleaboutthenumberofSaveSlotsandSavePointsyouareusing.Aimingforsomethinglike1SaveSlotand10SavePoints(or10SaveSlotswithoutSavepoints)wouldbemoreappropriate:

Page 36: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page36

1024K/(10saveslots*1SavePoints)=102.4Kmaxstoragepersavepoint

Thiswouldgiveyouaround100Kmaxpersavepoint.Youwouldalsoneedtoaccountforglobaldatabeingusedaswellasoverhead.Tobesafe,aimfor50%ofyourtheoreticalmaximumandkeepaneyeonitthroughoutdevelopment.

Do I Need Save Slots? Ifyouarebuildingarelativelystraightforwardgamethatfollowsasingleplayer/character,theanswertothisquestionislikelytobeno.Inthisscenario,SaveSlotsshouldbedisabled(internally,DataKitwillstillusethefirstSaveSlotbutyouwon'tneedtothinkaboutit).

Anotheroptionforsimplegames(orasadirectreplacementforanexistinggamethatisalreadyusingPlayerPrefs)istoonlyuseGlobalDataanddisableSaveSlotandSavePointfeatures.Thebenefitofthiskindofsetupisyou'llessentiallyhaveareplacementforPlayerPrefswithsupportforserializingallDataKit-compatibletypes,alongwiththeoptionalResourceDatabaseandrealtimevisualdebuggingintheEditor.

IfyouarebuildingsomethinglikeanRPG,oragamewhereyouwanttoallowaplayertohavemultiplecharactersthattrackthegameindependentlyfromeachother,youwillalmostcertainlybenefitfromSaveSlots.

IfyouenableSaveSlots,youmustchoosehowtocommunicateittotheplayerasitisanabstractconceptinDataKit.Youmaychoosetousetheterm"SaveSlot","CharacterSlot","PlayerAccount",oranythingelsethatmakessenseinyourownproject.

Do I Need Save Points? Ifyouwanttotrackaplayer'sprogressthroughoutagamesoitcanrememberanearlierstate(atapreviouslevel,withadifferentsetofitems,etc.)thenyouwilllikelywanttoenableSavePoints.

Ifyouonlywanttosaveasinglestateoftheplayer'sprogress(usuallythemostcurrent),youshoulddisableSavePoints(internally,DataKitwillstillusethefirstSavePointbutitwillbehandledforyou).ThistypeofscenariowouldworkwellforsimplearcadegamesorevenafreemiumstylewebgamesuchasClashofClanswherethereisonly1savedgamestate.

Do I Need To Capture Screenshots? IfyouwanttodisplaysmallthumbnailsinyourSave/Loadscreens,DataKitcanautomaticallyhandlethisforyou.Eventhoughcompressionisused,itstillrequiresaround20kofdiskspacewithtypicalsettings.

Page 37: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page37

IfyouarenotusingSavePoints(orusingPlayerPrefswherediskspaceisaconcern),youmaywanttoconsiderdisablingautomaticscreenshotsasyou'lllikelynotwanttodisplaythethumbnails.

How Do I Differentiate Between Local And Global Data? Thenextthingyoushoulddoisdeterminewhichpartsofyourgamesshouldbesavedasglobaldataandwhatshouldbesavedaslocaldata(SavePoints).

ThinkofGlobalDataasinformationthatshouldbethesamenomatterwhatplayerorSavePointisbeingused.GreatexamplesofGlobalDatainclude:

- GameSettings(Graphics,Audio,Preferences,InputBindings,etc.)- TrackingStorePurchasessuchasIAP(In-AppPurchases)andDLC

(Downloadablecontent).

LocalDataisbestsuitedtotracktheplayer'sprogressthroughoutagame.Excellentexamplesofthisinclude:

- ThelastUnityscenetheplayerwason(soyoucanloadit)- Player'scurrentlevel,score,currency,etc.- Inventories,collecteditems,etc.

How Should I Setup My Data Groups? IfyouonlyneedtosaveafewDataKeyssuchasthenameofthecurrentUnitysceneandtheplayer'sscore,thereisnoreasontocreatemultipleDataGroups.

Inthisscenario,youcouldsimplyhaveasingleDataGroupnamed"Data"andhavethekeysyouneedwithinit.Anexampleofthissetupoflocaldataisontheright.

Ifyoudohavealotofdatatosave,itmakessensetosplitthemupintogroups.Thisisalsoagreatwaytospeeduplookupswhenaccessinglargelistsofdatakeys.

How Should I Name My Data Groups And Keys? Therearenostrictruleshere.However,itisrecommendedtonamingtokeepthenamesofDataGroupsandKeysasshortaspossible.

Makingthemsoshortthattheyyoudon'trecognizewhattheyarewhendebuggingisoverkillbutbeawarethatshorterkeysarebetterbothforstorageandperformancereasons.

Page 38: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page38

What Type Of Data Should I Save To My Keys? DataKitshouldgenerallybeabletoserializealmostanydatatypefromthe'SupportedTypes'list.Thisincludesarrays,lists,dictionaries,customclasses,structsandmore.

StandardDataTypesArePreferred

IntheDataKitDebugger,youhavetheabilitytoenablereal-timeserializationtoviewandedityourdatainrealtime.However,tokeepthesystemreliableandfastintheEditor,real-timedebuggingiscurrentlydisabledforarraysorcustomclassesandstructs(onlythenameofthekeyandthetypeofdatawillbeviewableinthiscase).

TofullytakeadvantageoftheDataKitDebuggeritisrecommendedtosticktoasingleDataTypeperkeyratherthanarraysandclasseswhereverpossible.i.e.,ineachkeyyoushouldaimtoserializeasinglestring,float,Vector3,etc.

Theadvantagesindoingthisarenumerous.Itmakesserialization/deserializationfasterandmorereliablebyseparatingoutthedataintoothergroupsandkeys,aswellasmakingdevelopmentmucheasierbybeingabletoquicklyviewandedityourdatainrealtimewhilethegameisrunning.

…ButINeedMyDataKeyToBeAnArrayOrCustomClass!

Ifcertainpartsofyourgamemustbeserializedasaclassorarrayandyou'rehappyaboutnotviewingthedataliveintheDebugger,thisisstillsupported!

WhencreatingcustomclassesandstructsyouwanttoserializewithDataKit,makesuretheyarepublicandmarkedwiththe[Serializable]attribute.AnexampleofaSerializableclassisbelow:

// Example of how to setup a class to be serialized by DataKit [System.Serializable] public class ThisClassCanBeSerialized { public string playerName = "Player"; public int playerScore = 0; }

NOTE:Itisrecommendedtouseclassesratherthanstructswhenserializingcustomdata.

Shall I Save Large Assets Normally Or Use The New External Asset System? Ifyou'reusingthe'LocalFiles'storagemodeanddon’tneedtoshareyourgamedatatootherservers,youmaychoosetosavelargeassetsusingthenewExternalAssetssysteminDataKitV2.

Page 39: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page39

ThisallowsyoutosaveanassettoakeyandhaveDataKitautomaticallylinkittoanexternaldatafilewithouthavingtoworryaboutfilepaths,etc.CheckouttheExternalAssetAPIformoreinformation.

IfyouneedaccesstoserversormayneedtotargetplatformssuchasWebGL,youshouldsticktothestandardSetLocalAsset/SetGlobalAssetmethodswhicharecrossplatform.Becarefultomanageyourdiskspacethough!

The Risks Of Using Certain Data Types ThereislikelyagoodreasonwhyUnity'sPlayerPrefssystemdoesn'tofferanythingotherthanintegers,floatsandstrings.

Theseprimitivedatatypesareprettymuchfixedforthelongtermandnotsubjecttochange.Thingslikefloats,strings,longs,Vector3,etc.areveryunlikelytobemodifiedandsoareconsideredtobefarmore'future-proof'thansomethinglikeaUnityComponentoraparticularreferencetype.

Thisiswhyitisrecommendedtosticktovaluetypesandtoavoidreferenceswhereverpossibleunlessyouabsolutelyneedit.BychoosingtousereferencesandtypesthataresubjecttochangewithUnityupdates,youaretakingonthatriskforthefuture.DataKitwillevolvetosupportthelatestUnityversionsanddatatypesbutitmaynotalwaysbepossibletobridgethegapbetweenanoldertypeandanupdatedone.

Herearesomedatatypeswebelieveminimizetherisksandhelpkeepyourgamefuture-proof:PrimitiveValueTypesSuchAs:int,float,string,byte,bool,char,long,short,uint,ulong,ushort,Enum,andDateTime.CoreUnityValueTypesSuchAs:Bounds,Color,Color32,Matrix4x4,Quaternion,Rect,Vector2,Vector3,andVector4.

Page 40: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page40

DataKit API TheDataKitstaticclasshasnumerousmethodsandeventsthatareavailableviatheAPI.Remembertoadd“usingHellTap.DataKit;”atthetop!

Timing Is Everything It'simportanttorememberthatDataKitrunsinthebackgroundovermanyframes.Oneofthemorecriticalaspectstothisisknowingyourdatawillnotbereadywhenthegamebegins.DataKitrunsinthebackgroundandmustfirstscanandaccessexternalfiles,buildasavepointmap,setuptheReferenceDatabaseandthenloadinsaveddatabeforeitfiresthe'OnInitialized'Event.

Thisprocesscantakeseveralsecondswhichshouldnormallycompleteduringtheintroductionofyourgame(duringsplash/loadingscreens,etc.).AnexampleofaDataKitloadingscreenisprovidedandcanbefoundin"TheDataKitDemos"folderinyourproject.YoushouldincludesomethinglikethisinyourowngametoallowDataKitandanyotherpluginsyouhavetoinitializebeforetryingtoaccessyourdata.

Preloading DataKit In The Editor WhiletestingoutasceneintheUnityEditor,DataKithasanawesomewaytosimulategoingthroughthestandardsplash/loadingscreenswithouthavingtochangefromthesceneyou'reworkingon.DataKit'spreloadingfeaturecouldn'tbeeasier-Justpress"Play"intheEditorasnormal!

DataKitwillautomaticallyrememberthesceneyouwereworkingon,loadtheDataKitpreloaderscene,initializeitselfandthenchangescenesbacktowhereyouwere.ThisplacesDataKitinan'initialized'statewhenyourscenebegins.

The"PreloadDataKitInEditor"optionintheDataKitSetupassetallowsyoutoturnthisbehavioronandoff.Thisworksgreatwiththe"LoadGlobalAndLatestSavePoint"initializationoption,whichtellsDataKittoautomaticallyloadthenewestSavePointfromaspecificSaveSlotyouchoose.

ThismakeseverythingsomucheasiertoworkwithandyoushoulddefinitelybecomeaccustomedtothefeaturetohelpyougetthemostoutofworkingwithDataKit.PleasenotethatDataKit'sautomaticpreloadingfeatureisonlyavailableintheEditor,sobesuretoincludeaninitialsplash/loadingscreeninyourgametowaitforDataKittoinitialize(feelfreetousetheexampleloadingscreenprovidedinthe"DataKitDemos"folder).

Page 41: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page41

Example Code – The Basics ThissectioncoversthebasicsofscriptingwithDataKit.

Namespaces

ToworkwithDataKit,besuretoaddthiscodeatthetopofyourscripts:

using HellTap.DataKit;

MakeSureDataKitIsReady

Beforeattemptingtoget/setanydatakeyyoushouldalwaysbesurethatDataKitis'Ready'.ThismeansthatDataKitis'initialized'andisnotcurrentlyperforminganyfileoperations.

Aquickwaytodothisisusingthefollowingcodesnippet:

if( DataKit.IsReady() ){ // DataKit Is Ready! }

SavingData

Tosavesomedatatoaglobalkey,youcanusethefollowingcode:

DataKit.SetGlobalKey( "MyGroup", "MyKey", 5 );

Thecodesnippetabovesetsthevalue5toakeynamed"MyKey",insideofagroupnamed"MyGroup"withinGlobalData.

Tosavethesamekeytolocaldata(inorderforittolaterbecomeaSavePoint),thesyntaxisverysimilar:

DataKit.SetLocalKey( "MyGroup", "MyKey", 5 );

LoadingData

Toloadthesameglobalkeybacktoavariable,youcanusethefollowingsyntax:

var myInt = DataKit.GetGlobalKey<int>( "MyGroup", "MyKey" );

NOTE:YoumusttellDataKitwhatdatatypethekeyisasitisusingagenericmethod(inthiscase,itisan'int').Loadinglocaldataisalmostidentical:

var myInt = DataKit.GetLocalKey<int>( "MyGroup", "MyKey" );

Page 42: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page42

LoadingDataWithDefaultValues

Youcanchoosetoloadaglobalkeyalongwithpresetdefaultdata(justincaseitdoesn'texistorthereisaproblemdeserializingduetodatacorruption).Youcanusethefollowingsyntax:

var myInt = DataKit.GetGlobalKey<int>( "MyGroup", "MyKey", 5 );

Intheexampleabove,iftherewasaproblemgettingtheintegervalueofmyInt,thevalue5willbereturnedinstead.

Asusual,thelocaldataversionofthisfollowsthesameformat:

var myInt = DataKit.GetLocalKey<int>( "MyGroup", "MyKey"", 5 );

DefaultDataGroups

IfyouhavearelativelysimplegamewithonlyasingleDataGroupbeingused,youmaychoosetocodeusingthe'DefaultDataGroup'fieldsfoundintheDataKitSetupasset.YoucanalsoexplicitlysetitviatheAPIlikethis:

DataKit.SetDefaultGlobalGroup( "MyGroup" ); DataKit.SetDefaultLocalGroup( "MyGroup" );

Thiscanbeusedinplaceofthegroupparameter.Forexample,ifwe'vesetupthe'DefaultDataGroup'forglobaldatatobe'MyGroup',wecouldtakethefollowingcodesnippet:

DataKit.SetGlobalKey( "MyGroup", "MyKey", 5 );

Andusethisshorterversioninstead:

DataKit.SetGlobalKey( "MyKey", 5 );

Thesamecanbeachievedwhengettingdatatoo:

var myInt = DataKit.GetGlobalKey<int>( "MyKey" );

Codingwith'DefaultDataGroups'workswithbothlocalandglobaldata!

However,ifyouwanttogetsomedatawithoutsupplyingagroupnameandalsoprovideadefaultvalueatthesametime,youcoulduseamethodnamed'GetGlobalKeyInDefaultGroup'(or'GetLocalKeyInDefaultGroup'ifitislocaldata).Thismayormaynotbeshorterthanjustsupplyingall3parameters,buttheoptionisthere!J

var myInt = DataKit.GetGlobalKeyInDefaultGroup<int>( "MyKey", 5 );

NOTE:EventhoughitisnotexplicitlystatedinlatersectionsoftheAPI,mostmethodsthatrequireagroupnameandkeyalsosupportdefaultgroups!

Page 43: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page43

CheckingIfADataGroupExists

YoucaneasilycheckifADataGroupExistslikethis:

if ( DataKit.HasGlobalGroup( "MyGroup" ) ){ // "MyGroup" is the name of a group inside of Global Data! }

Thesamecanbeachievedwithlocaldatalikethis:

if ( DataKit.HasLocalGroup( "MyGroup" ) ){ // "MyGroup" is the name of a group inside of Local Data! }

CheckingIfADataKeyExists

YoucaneasilycheckifaGlobalDataKeyExistslikethis:

if ( DataKit.HasGlobalKey( "MyGroup", "MyKey" ) ){ // "MyKey" exists in "MyGroup" of Global Data! }

Thesamecanbeachievedwithlocaldatalikethis:

if ( DataKit.HasLocalKey( "MyGroup", "MyKey" ) ){ // "MyKey" exists in "MyGroup" of Local Data! }

SavingReferencesByValue(SavingAssets)

Youcaneasilysavesupported'SpecialReferenceTypes'byvalueinsteadofreferencebyusingDataKit's'SetGlobalAsset'and'SetLocalAsset'methods.

YoushouldnotethatsavingreferencesthiswaycansignificantlyincreasethefilesizeofyourSavePointssoyoushouldusethiswisely.

ManyreferencessuchasTexture2D,Audioclip,Meshesandmorecanbedirectlyserializedthisway(thesereferencesdonotneedtobepartoftheReferenceDatabasesystemtobeserialized!).

AudioClips,Materials,Meshes,PhysicMaterialsandPhysicMaterial2Dscanbeserializedtoglobaldatalikethis:

DataKit.SetGlobalAsset( "MyGroup", "MyKey", myAsset );

YoucanserializeittolocaldatawiththeSetLocalAssetmethod:

DataKit.SetLocalAsset( "MyGroup", "MyKey", myAsset );

Page 44: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page44

Texture2DsandSpritescanbeserializedtoglobaldatalikethis:

DataKit.SetGlobalAsset( "MyGroup", "MyKey", myAsset, "jpg", 50 );

Theextra2parametersattheendare'format'and'quality'.Thisisusedtodeterminethequalityoftheserializedimage.Inthiscase,wearesavingtheimageasa"jpg"withaqualityof50%.Youcouldalternativelyuse"png"(althoughthequalityvalueisignoredwhenusingthePNGformat).

Inthesameway,youcansaveassetstoLocalDatalikethis:

DataKit.SetLocalAsset( "MyGroup", "MyKey", myAsset, "jpg", 50 );

ExternalAssets('LocalFiles'StorageModeOnly)

Ifyou'reusingtheLocalFilesasyourstoragemode,youmayprefertousethenewExternalAssetsystemintroducedinDataKitV2ratherthantheuniversallysupportedSetLocalAsset/SetGlobalAssetmethods.

ThebenefitsofthisistohaveDataKitusemulti-threadingtoautomaticallyestablishalinkbetweenadatakeyandanactualexternalfileinsideoftheSavePointfolder.Allyouneedtodoisset/getit,andDataKithandlestherestwhilekeepingyourmaindatafilesmallandblazinglyfast!

ItworksinthesamewayastheSetLocalAssetmethod.Tosaveanexternalassetasapngwith100%qualitytoalocaldatakey,youcandoitlikethis:

DataKit.SaveLocalExternalAsset( "MyGroup", "MyKey", myAsset, "png", 100 );

Tosavetheassettoaglobaldatakey,thefollowingmethodisusedinstead:

DataKit.SaveGlobalExternalAsset( "MyGroup", "MyKey", myAsset, "png", 100);

ToloadanExternalAsset,youmustusetheLoadLocalExternalAsset()orLoadGlobalExternalAsset()methods,likethis:

var tex = DataKit.LoadLocalExternalAsset<Texture2D>( "MyGroup", "MyKey );

RevertingData

Youcanrevertadatakeybacktoitsdefaultvalue(setintheDataKitSetupasset).Notethatifthiskeywascreateddynamicallyatruntime,revertingisignored.YoushouldalsobeawarethatifyourevertakeythatislinkedtoanExternalAsset,DataKitwillautomaticallydeletetheexternalassetfilesobecareful!

DataKit.RevertGlobalDataKey( "MyGroup", "MyKey" );

Page 45: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page45

Thecodeabovewillset"MyKey"insideof"MyGroup"ofGlobalDatabacktoitsdefaultvalue.Thesamecanbeachievedforlocaldatalikethis:

DataKit.RevertLocalDataKey( "MyGroup", "MyKey" );

DataKitalsoallowsyoutorevertentiredatagroups,likethis:

DataKit.RevertGlobalDataGroup ( "MyGroup" );

NOTE:Thisactionmaydeletekeysthatalreadyexistaswellascreatenewones.Itspurposeistorevertagroupofdatabacktodefaultvalues.Thelocaldataversioncanbeusedlikethis:

DataKit.RevertLocalDataGroup ( "MyGroup" );

Youcaneasilyrevertallglobaldatagroupslikethis:

DataKit.RevertAllGlobalData();

Alllocaldatagroups:

DataKit.RevertAllLocalData();

Finally,aconvenientmethodtorevertalllocalandglobaldatabacktodefaultscanbedonelikethis:

DataKit.RevertAllData();

Page 46: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page46

Example Code - OnInitialized TherecommendedapproachwhenworkingwithDataKitistousetheeventsystem.DataKiteventsgiveyouupdatesonthelow-levelfileoperationsbeingperformedautomatically(Ifthesystemisinitialized,savingandloadingdata,etc.).YoushouldusetheseeventstoletyouknowwhenDataKitisreadyforyoutostartsettingandgettingdata.

TheexamplebelowshowsatypicaltemplatetostartreceivinginformationfromDataKit.We'llfocusinonthe'OnInitialized'event:

// ShowConsoleMessageWhenDataKitIsInitialized.cs // This example script demonstrates how to correctly subscribe to DataKit // and show a console message when the system has been initialized. using UnityEngine; using HellTap.DataKit; public class ShowConsoleMessageWhenDataKitIsInitialized : MonoBehaviour { // -------------------------------------------------- // ON ENABLE // -------------------------------------------------- void OnEnable(){ // Subscribe to the DataKit Events we need DataKit.OnInitialized += OnInitialized; // If DataKit was ready before this is enabled, setup immediately if( DataKit.IsReady() ){ OnInitialized(); } } // -------------------------------------------------- // ON DISABLE // -------------------------------------------------- void OnDisable(){ // Unsubscribe From DataKit Events DataKit.OnInitialized -= OnInitialized; } // -------------------------------------------------- // ON INITIALIZED // This should only run the first time DataKit is ready // -------------------------------------------------- // When DataKit Is Ready for the first time, Run Our Code... public void OnInitialized(){ Debug.Log("DATAKIT IS INITIALIZED!"); // We can now safely access Global and Local Data Keys! } }

Page 47: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page47

Let'stakeacloserlookatthecodeexampleaboveandbreakitdownsowecanunderstandwhatishappening:

using HellTap.DataKit;

First,weshouldalwaysremembertoaddthe"usingHellTap.DataKit;"lineonourscripts.ThisallowsustodirectlycalltheDataKitAPI.

void OnEnable(){

The'OnEnable'methodisfiredshortlyafterthescriptisloaded.Itisassumedherethatthisscriptwon'tbedestroyed(ordisabled)untilweleavethescene.

DataKit.OnInitialized += OnInitialized;

WethensubscribetoDataKit's'OnInitialized'Event.ThisEventwillonlyfirethefirsttimeDataKitbecomesready.Ifthishasn'thappenedyet,DataKitwillcallour'OnInitialized'methodwhenitdoes.

if( DataKit.IsReady() ){ OnInitialized(); }

ThenextsectionchecksifDataKitisready(thismeansitisinitializedandnotperformingfileoperations).IfwefindthatDataKitwasalreadyinitializedandreadybeforethescriptwasloaded(mostlikelyfromapreviousUnityScene),we'llgoaheadandrunourOnInitializedmethodrightaway.

void OnDisable(){ // Unsubscribe From DataKit Events DataKit.OnInitialized -= OnInitialized; }

Next,wehandlethe'OnDisable'method.Thisiscalledwhenthescriptisdisabled(ordestroyed).InthismethodwesimplyunsubscribefromreceivingDataKit's'OnInitialized'Event.

public void OnInitialized(){

Debug.Log("DATAKIT IS INITIALIZED!"); // We can now safely access Global and Local Data Keys!

}

Finally,wesetupour'OnInitialized'methodwhichiscalledthefirsttimeDataKitisinitializedandbecomesready(sincethescriptwasenabled).Inthisexample,we'resimplyprintingamessagetotheconsole.NowthatDataKitisinitializedandready,wewouldtypicallyextendthecodetostartloadingdataintoourgame.

Page 48: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page48

Example Code – OnReady and OnNotReady Inthelastsectionweexaminedthe'OnInitialized'Event,whichtriggersthefirsttimeDataKitbecomesready.

Thistime,we'lltakealookatthe'OnReady'Event.ThiseventissimilartoOnInitializedbutwilltriggereverytimeDataKitgoesfrombeing'NotReady'to'Ready'.We'llalsoincludethe'OnNotReady'Eventtoo.

// ShowConsoleMessagesAsDataKitStateChanges.cs // This example script demonstrates how to correctly subscribe to DataKit // and show a console message as DataKit's state changes. using UnityEngine; using HellTap.DataKit; public class ShowConsoleMessagesAsDataKitStateChanges: MonoBehaviour { // -------------------------------------------------- // ON ENABLE // -------------------------------------------------- void OnEnable(){ // Subscribe to the DataKit Events we need DataKit.OnInitialized += OnInitialized; DataKit.OnReady += OnReady; DataKit.OnNotReady += OnNotReady; // If DataKit was ready before this is enabled, setup immediately if( DataKit.IsReady() ){ OnInitialized(); // Otherwise, run the actions in the OnNotReady method immediately } else { OnNotReady(); } } // -------------------------------------------------- // ON DISABLE // -------------------------------------------------- void OnDisable(){ // Unsubscribe From DataKit Events DataKit.OnInitialized -= OnInitialized; DataKit.OnReady -= OnReady; DataKit.OnNotReady -= OnNotReady; } // ... Code continues on the next page ->

Page 49: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page49

// <- Continued ... // --------------------------------------------------

// ON INITIALIZED // This should only run the first time DataKit is ready // -------------------------------------------------- public void OnInitialized(){ Debug.Log("DATAKIT IS INITIALIZED!"); }

// -------------------------------------------------- // ON READY // This runs EVERY time DataKit becomes ready // -------------------------------------------------- public void OnReady(){ Debug.Log("DATAKIT IS READY!"); }

// -------------------------------------------------- // ON NOT READY // Runs EVERY time DataKit performs file operations. // -------------------------------------------------- public void OnNotReady(){ Debug.Log("DATAKIT IS NOT READY!"); } }

Let'sseewhathaschangedsincethelastexample:

// Subscribe to the DataKit Events we need DataKit.OnInitialized += OnInitialized; DataKit.OnReady += OnReady; DataKit.OnNotReady += OnNotReady;

Thefirstthingyou'llnoticeisintheOnEnablemethod.Here,we'resubscribingtothreeofDataKit'sevents:'OnInitialized','OnReady'and'OnNotReady'.Wethenmoveontothenextpartofthecode:

// If DataKit was ready before this is enabled, setup immediately if( DataKit.IsReady() ){ OnInitialized(); // Otherwise, run the actions in the OnNotReady method immediately } else { OnNotReady(); }

Justlikethepreviousexample,wefirstcheckifDataKit'IsReady'.Ifitis,werunthe'OnInitialized'methodinthescriptrightaway.

Page 50: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page50

Aswe'realsotrackingthe'IsNotReady'event,wecanalsoimmediatelyrunthoseactionsifweneedto(thisistotallyoptionalanddependsonyourowncode).

// Unsubscribe From DataKit Events DataKit.OnInitialized -= OnInitialized; DataKit.OnReady -= OnReady; DataKit.OnNotReady -= OnNotReady;

ThenextdifferenceisintheOnDisablemethod.Aswe'vesubscribedtoextraDataKitEvents,weneedtomakesurewecleanlyunsubscribefromthemwhenthescriptisdisabledordestroyed.

Lastly,wehavethethreecallbackmethods:

public void OnInitialized(){ Debug.Log("DATAKIT IS INITIALIZED!"); }

Wealreadyknowaboutthe'OnInitialized'method.Itisagoodideatoputanysetupcodethatshouldonlyrunonceinthismethod.

public void OnReady(){ Debug.Log("DATAKIT IS READY!"); }

The'OnReady'methodissimilarto'OnInitialized'butwillruneverytimeDataKitbecomesready.Italsorunsafter'OnInitialized'iscalled.UsethiseventtorunanyactionsthatshouldhappenwhenDataKitentersastatetoget/setdata.

public void OnNotReady(){ Debug.Log("DATAKIT IS NOT READY!"); }

Lastly,wehavethe'OnNotReady'method.YoucanusethistoperformanyactionsthatshouldhappenwhenDataKitentersastatewherefileoperationsaretakingplace.YoushouldnotattempttoaccessDataKitdatawhileinthisstate.

HopefullythisexamplecodeillustrateshowyoucancontinuetogetmoreinformationfromDataKitbysubscribingtoadditionalevents.

ThefollowingpagelistsalloftheDataKiteventsthatareavailabletohelpyoubuildyourscripts.

Page 51: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page51

Events DataKitworksinthebackgroundandhasacomprehensivelistofEventsthatcanbeusedtostructureyourcode.TheEventsareusedtogetinformationaboutDataKit'sfileoperationsandwhenitissafetostartreadingandwritingdata.Justlikeinthepreviousexamples,youcanaddanyoftheseeventsinthesameway:

DataKit.OnInitializedEventthattriggerswhenDataKithasfirstbeeninitializedandIsReady(triggersonce).Usethisforinitialsetup.DataKit.OnReadyEventthattriggerswhenDataKit.IsReady()==true.Thismeansnofileoperationsaretakingplace.DataKit.OnNotReadyEventthattriggerswhenDataKitIsReady()==false.Thismeansfileoperationsaretakingplace.DataKit.OnSaveLocalDataStartedEventthattriggerswhenanattempttocreateanewsavepointhasstarted

DataKit.OnSaveGlobalDataStartedEventthattriggerswhenanattempttosavenewglobaldatahasstarted

DataKit.OnSaveLocalDataSuccessfulEventthattriggerswhenanewsavepointhasbeensavedsuccessfully

DataKit.OnSaveGlobalDataSuccessfulEventthattriggerswhennewglobaldatawassavedsuccessfully

DataKit.OnSaveLocalDataFailedEventthattriggerswhenanewsavepointfailedtobesaved

DataKit.OnSaveGlobalDataFailedEventthattriggerswhennewglobaldatafailedtobesaved

DataKit.OnLoadLocalDataStartedEventthattriggerswhenanattempttoloadanexistingsavepointhasstarted

DataKit.OnLoadGlobalDataStartedEventthattriggerswhenanattempttoloadglobaldatahasstarted

DataKit.OnLoadLocalDataSuccessfulEventthattriggerswhenanewsavepointhasbeenloadedsuccessfully

DataKit.OnLoadGlobalDataSuccessfulEventthattriggerswhenglobaldatahasbeenloadedsuccessfully

DataKit.OnLoadLocalDataFailedEventthattriggerswhenanewsavepointfailedtobeloaded

DataKit.OnLoadGlobalDataFailedEventthattriggerswhenglobaldatafailedtobeloaded

DataKit.OnDeleteSavePointSuccessfulEventthattriggerswhenasavepointhasbeendeletedsuccessfully

DataKit.OnDeleteSavePointFailedEventthattriggerswhenfailingtodeleteasavepoint

DataKit.OnDeleteSaveSlotSuccessfulEventthattriggerswhenasaveslothasbeendeletedsuccessfully

DataKit.OnDeleteSaveSlotFailedEventthattriggerswhenfailingtodeleteasaveslot

Page 52: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page52

DataKit.OnDeleteAllSaveSlotsSuccessfulEventthattriggerswhenallsaveslotshavebeendeletedsuccessfully

DataKit.OnDeleteAllSaveSlotsFailedEventthattriggerswhenfailingtodeleteallsaveslots

Core Methods HerearealistofDataKit'scoremethods:DataKit.IsReady(boolshowWarnings=false):Returnsbool

ReturnstrueifDataKitisinitializedandnotperformingfileoperations.Ifthe'showWarnings'parameterissettotrue,aconsolemessagewillalsobedisplayedifDataKitisnotready.

If( DataKit.IsReady() ){ // DataKit Is Ready ... }

DataKit.IsReferenceDatabaseReady():Returnsbool

ReturnstrueifDataKit'sReferenceDatabasehasfinishedsettingitselfup.

If( DataKit.IsReferenceDatabaseReady() ){ // Reference Database Is Ready ... }

DataKit.GetCurrentNumberOfReferenceResolversLoaded():ReturnsintThisallowsustoquerytheprogressofloadingandpreparingtheReferenceDatabasewhileDataKitissettingitselfup.HowmanyReferenceResolvershavebeenloadedalready?

int refsLoaded = DataKit.GetCurrentNumberOfReferenceResolversLoaded();

DataKit.GetTotalNumberOfReferenceResolversToLoad():ReturnsintThisallowsustoquerytheprogressofloadingandpreparingtheReferenceDatabasewhileDataKitissettingitselfup.HowmanyReferenceResolversarethereintotalthatweneedtoload?

int totalRefsToLoad = DataKit.GetTotalNumberOfReferenceResolversLoaded();

DataKit.GetProgressOfLoadingReferenceResolvers():ReturnsfloatThisallowsustoquerytheprogressofloadingandpreparingtheReferenceDatabasewhileDataKitissettingitselfup.Returnsa0fto1fvaluetobeusedwithprogressbars,etc.

progressBar.fillAmount = DataKit.GetProgressOfLoadingReferenceResolvers();

DataKit.GetStorageType():ReturnsstringReturnstheformatofDataKit'scurrentStoragemodeasastring.Returnsanemptystringifnotready.

Debug.Log( "DataKit Storage Mode: " + DataKit.GetStorageType() );

DataKit.SetCurrentSaveSlot(intslot):voidThisallowsustoswitchtoanewsaveslotusinga1-basedindex.Use1forslot1,2forslot2,etc.

DataKit.SetCurrentSaveSlot( 1 );

Page 53: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page53

DataKit.GetCurrentSaveSlot():ReturnsintThisallowsustogetthecurrentsaveslotasaninteger.

int whatSaveSlotAreWeUsing = DataKit.GetCurrentSaveSlot();

DataKit.GetNumberOfSaveSlots():ReturnsintHowmanysaveslotscanweuse?

int howManySaveSlotsAreThere = DataKit.GetNumberOfSaveSlots();

DataKit.GetEmptySavePointCount():ReturnsintReturnshowmanyemptysavepointsareavailableinthecurrentsaveslot

int howManyEmptySavePointsAreThere = DataKit.GetEmptySavePointCount();

DataKit.GetUsedSavePointCount():ReturnsintReturnshowmanysavepointshavebeencreatedinthecurrentsaveslot

int howManySavePointsHaveBeenCreated = DataKit.GetUsedSavePointCount();

DataKit.GetSavePointLimit():ReturnsintReturnsthemaximumnumberofsavepointsallowedperslot

int howManySavePointsCanBeSavedPerSlot = DataKit.GetSavePointLimit();

DataKit.GetAutomaticallyReplaceOldSavePoints():ReturnsboolReturnstrueiftheoldestsavepointissettobeautomaticallydeletedwhentheSavePointlimitisreached.

bool areWeAutoDeletingSavePoints = DataKit.GetAutomaticallyReplaceOldSavePoints();

DataKit.GetSavePointDescriptions():Returnsstring[]Returnsastringarrayofallsavepointdescriptionsinthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

string[] savePointDescriptions = DataKit.GetSavePointDescriptions();

DataKit.GetSavePointTimestamps():Returnslong[]Returnsalongarrayofsavepointtimestampsinthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

long[] savePointTimestamps = DataKit.GetSavePointTimestamps();

DataKit.GetFormattedSavePointTimestamps():Returnsstring[]Returnsapre-formattedstringarrayofsavepointtimetampsinthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

string[] formattedSavePointTimestamps = DataKit.GetFormattedSavePointTimestamps();

Page 54: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page54

DataKit.GetSavePointByteLengths():Returnslong[]Returnsalongarrayofsavepointbytelengths(est.filesize)inthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

long[] savePointByteLengths = DataKit.GetSavePointByteLengths();

DataKit.GetFormattedSavePointFileSize():Returnsstring[]Returnsastringarrayofpre-formattedsavepointbytelengths(asKB)inthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

string[] formatedSavePointFileSizes = DataKit.GetFormattedSavePointFileSize();

DataKit.GetSavePointScreenshots():ReturnsTexture2D[]ReturnsaTexture2DarrayofsavepointScreenshotsinthecurrentsaveslot.Thisusestheorderandindexoftheinternalsavepointmap.Sortedfromnewesttooldest.

Texture2D[] savePointScreenshots = DataKit.GetSavePointScreenshots();

Screenshot Methods Thefollowingmethodsrevolvearoundcapturingscreenshotstobeusedasthumbnails:

DataKit.TakeScreenshot(ActiononSuccess=null,ActiononFail=null):voidCreatesandSavesascreenshottothecurrentlocaldata.Callbacksarealsoavailable.

DataKit.TakeScreenshot();

DataKit.SetScreenshot(Texture2DnewScreenshot,DataKitSerializer.SaveAssetFormatformat=DataKitSerializer.SaveAssetFormat.JPG,intquality=50):voidAllowsustosupplyaTexture2Dtobeserializedandstoredasthescreenshotthumbnailinlocaldata.

DataKit.SetScreenshot( myTexture2D );

DataKit.GetScreenshot():ReturnsTexture2DAttemptstoretrievethecurrentlysavedscreenshotinlocaldata.

Texture2D screenshotFromLocalData = DataKit.GetScreenshot();

File Management Methods Thefollowingmethodscanbeusedtohandlefilemanagement:DataKit.AutoSave(stringsaveGameDescription=emptyString,ActiononSuccess=null,ActiononFail=null):void

Auto-capturesscreenshot(ifenabled),createstheautosavetextdescriptionandcreatesanewSavePointalongwithsavingthemostcurrentglobaldata.Optionalcallbacksarealsoavailable.

DataKit.AutoSave();

Page 55: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page55

DataKit.AutoLoad(ActiononSuccess=null,ActiononFail=null):voidAttemptstoautomaticallyLoadgamedatafromthethenewestsavepointinthisSaveSlot.Optionalcallbacksarealsoavailable.

DataKit.AutoLoad();

DataKit.Save(stringsaveGameDescription=emptyString,boolcreateScreenshot=false,ActiononSuccess=null,ActiononFail=null):voidSaveslocaldatatoaSavePointandalsosavesthecurrentversionofGlobaldatatoo.Thisversionofthesavemethoddoesn'tusethe'auto-save'textdescriptionandgivesyoutheoptionofcreatingascreenshot.Callbacksarealsoavailable.

DataKit.Save( "My SavePoint Description", true );

DataKit.SaveGlobalData(ActiononSuccess=null,ActiononFail=null):voidSavesthecurrentglobaldatawithoutsavinglocaldata(buildingasavepoint).Optionalcallbacksarealsoavailable.

DataKit.SaveGlobalData();

DataKit.Load(intloadSavePointMapIndex=-1,ActiononSuccess=null,ActiononFail=null):voidLoadsgamedatafromtheindexoftheSavePointMap.Ifnoindexissupplied,thenewestsavepointisloadedbydefault(-1).Callbacksarealsoavailable.

DataKit.Load( 0 );

DataKit.LoadGlobalData(ActiononSuccess=null,ActiononFail=null):voidLoadsthelastsavedglobaldatawithoutloadinglocaldata(fromasavepoint).Optionalcallbacksarealsoavailable.

DataKit.LoadGlobalData();

DataKit.DeleteSavePoint(intdeleteSavePointIndex,ActiononSuccess=null,ActiononFail=null):voidDeletesasavepointinthecurrentlyselectedsaveslot.UsestheindexoftheSavePointMap.Optionalcallbacksarealsoavailable.

DataKit.DeleteSavePoint( 4 );

DataKit.DeleteSaveSlot(intsaveSlot=-1,ActiononSuccess=null,ActiononFail=null):voidDeleteallsavepointsinsideofasaveslot.IfthesaveSlotparameterisn'tset,thecurrentSaveSlotisused.Optionalcallbacksarealsoavailable.

DataKit.DeleteSaveSlot( 1 );

DataKit.DeleteAllSaveSlots(ActiononSuccess=null,ActiononFail=null):voidDeletesallsavepointsinsideofallsaveslots.Optionalcallbacksarealsoavailable.

DataKit.DeleteAllSaveSlots();

Page 56: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page56

Global Data Methods ThefollowingisalistofmethodsforhandlingGlobalData:

DataKit.CreateGlobalGroup(stringgroupName):voidCreatesanewgroupinglobaldatausingthenamesetinthe'groupName'parameter.

DataKit.CreateGlobalGroup( "New Group" );

DataKit.DeleteGlobalGroup(stringgroupName):voidDeletesanexistinggroupinglobaldata.

DataKit.DeleteGlobalGroup( "Existing Group" );

DataKit.SetDefaultGlobalGroup(stringgroupName):voidSetsanewgroupinglobaldatatobethedefaultgroup.

DataKit.SetDefaultGlobalGroup( "Default Group" );

DataKit.GetDefaultGlobalGroup():ReturnsstringGetsthecurrentdefaultgroupinglobaldata.

string defaultGroup = DataKit.GetDefaultGlobalGroup();

DataKit.CreateGlobalKey(stringgroupName,stringkey):voidCreatesanew'unassigned'keyinaglobaldatagroup.

DataKit.CreateGlobalKey( "MyGroup", "MyKey" );

DataKit.DeleteGlobalKey(stringgroupName,stringkey):voidDeletesanexistingkeyinaglobaldatagroup.

DataKit.DeleteGlobalKey( "MyGroup", "MyKey" );

DataKit.ResetGlobalKey(stringgroupName,stringkey):voidResetsanexistingkeyinaglobaldatagroup,maintainingitsoriginalname.Thisclearstheserializeddataandsetsthekeyasbeing'unassigned'.

DataKit.ResetGlobalKey( "MyGroup", "MyKey" );

DataKit.ResetAllGlobalKeysInGroup(stringgroupName):voidResetsallexistingkeysinaglobaldatagroup,maintainingtheiroriginalnames.Thisclearstheserializeddataandsetsthekeysasbeing'unassigned'.

DataKit.ResetAllGlobalKeysInGroup( "MyGroup" );

DataKit.ResetAllGlobalKeysInAllGroups():voidResetsallexistingkeysinallglobaldatagroups,maintainingtheiroriginalnames.

DataKit.ResetAllGlobalKeysInAllGroups();

Page 57: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page57

DataKit.HasGlobalGroup(stringgroupName):voidCheckstoseeifagroupexistsinglobaldata.

if( DataKit.HasGlobalGroup( "MyGroup" ) ){ // Global Group Exists! }

DataKit.HasGlobalKey(stringgroupName,stringkey):voidCheckstoseeifagroup/keyexistsinglobaldata.

if( DataKit.HasGlobalKey( "MyGroup", "MyKey") ){ // Global Key Exists! }

DataKit.SetGlobalKey<T>(stringgroupName,stringkey,TtoSerialize):voidSerializesanobjecttoaspecificglobalkeyusingthegroupNameandkey.

DataKit.SetGlobalKey( "MyGroup", "MyVector3", new Vector3( 1f, 2f, 3f ) );

DataKit.SetGlobalAsset<T>(stringgroupName,stringkey,TtoSerialize,stringformat,intquality=50):voidSavesasupportedreferenceasset(Texture2D,Audioclip,etc)byvaluesoitcanberecreatedatruntime.Ifusinganimage,makesuretouseeither"jpg"or"png"astheformat.IfusingtheJPGformat,youcanalsodefinethequalityasapercentage.Forothersupportedreferencetypes,settheformattoanemptystring.

DataKit.SetGlobalKey( "MyGroup", "MyKey", myTexture2D, "jpg", 50 );

DataKit.GetGlobalKey<T>(stringgroupName,stringkey):ReturnsTGetsanobjectfromaspecificglobalkeyusingthegroupNameandkey.Asthismethodusesgenerics,youmustsupplythedatatypebeforetheparameters.NOTE:Thiscanalsobeusedtoretrieveobjectssavedwiththe'SetGlobalAsset'method.

Vector3 myVector3 = DataKit.GetGlobalKey<Vector3>( "MyGroup", "MyVector3" );

DataKit.GetGlobalKey<T>(stringgroupName,stringkey,TdefaultData):ReturnsTGetsanobjectfromaspecificglobalkeyusingthegroupnameandkey.Thethirdfieldwillbereturnedifthegroup/keydoesn'texist.NOTE:Thiscanalsobeusedtoretrieveobjectssavedwiththe'SetGlobalAsset'method.

int myInt = DataKit.GetGlobalKey<int>( "MyGroup", "myInt", 0 );

DataKit.RevertGlobalDataGroup(stringgroupName):voidRevertsaglobaldatagroupbacktotheoriginalsettingsoftheDataKitSetupinspector.Ifthegroupdidn'talreadyexist,thiswillbeignored.Ifthegroupwasdeletedinthecurrentglobaldata,itwillberecreated.

DataKit.RevertGlobalDataGroup( "MyGroup" );

Page 58: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page58

DataKit.RevertGlobalDataKey(stringgroupName,stringkey):voidRevertsaglobaldatakeybacktotheoriginalsettingsoftheDataKitSetupinspector.Ifthegroup/keydidn'talreadyexist,Thiswillbeignored.Ifthegroup/keywasdeletedinthecurrentdata,itwillberecreated.

DataKit.RevertGlobalDataKey( "MyGroup", "myInt" );

DataKit.RevertAllGlobalData():voidRevertsallglobaldatabacktothedefaultsetupintheDataKitSetupinspector.

DataKit.RevertAllGlobalData();

DataKit.RevertAllData():voidRevertsbothlocalandglobaldatabacktothedefaultsetupintheDataKitSetupinspector.

DataKit.RevertAllData();

DataKit.GetDefaultGlobalDataKey<T>(stringgroupName,stringkey,TdefaultValue):ReturnsTAttemptstogetthedefaultvalueofaglobalkey(thedefaultvalueusedinDataKitSetup,notthecurrentvalue).Ifthisvaluedidn'toriginallyexist,thedefaultvaluesenttothemethodwillbereturnedinstead.Thisissimilartorevertingdataexceptthecurrentvalueinglobaldataisunaffected.

int myInt = DataKit.GetDefaultGlobalDataKey( "MyGroup", "myInt", 1 );

Page 59: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page59

Local Data Methods ThefollowingisalistofmethodsforhandlingLocalData:

DataKit.CreateLocalGroup(stringgroupName):voidCreatesanewgroupinlocaldatausingthenamesetinthe'groupName'parameter.

DataKit.CreateLocalGroup( "New Group" );

DataKit.DeleteLocalGroup(stringgroupName):voidDeletesanexistinggroupinlocaldata.

DataKit.DeleteLocalGroup( "Existing Group" );

DataKit.SetDefaultLocalGroup(stringgroupName):voidSetsanewgroupinlocaldatatobethedefaultgroup.

DataKit.SetDefaultLocalGroup( "Default Group" );

DataKit.GetDefaultLocalGroup():ReturnsstringGetsthecurrentdefaultgroupinlocaldata.

string defaultGroup = DataKit.GetDefaultLocalGroup();

DataKit.CreateLocalKey(stringgroupName,stringkey):voidCreatesanew'unassigned'keyinalocaldatagroup.

DataKit.CreateLocalKey( "MyGroup", "MyKey" );

DataKit.DeleteLocalKey(stringgroupName,stringkey):voidDeletesanexistingkeyinalocaldatagroup.

DataKit.DeleteLocalKey( "MyGroup", "MyKey" );

DataKit.ResetLocalKey(stringgroupName,stringkey):voidResetsanexistingkeyinalocaldatagroup,maintainingitsoriginalname.Thisclearstheserializeddataandsetsthekeyasbeing'unassigned'.

DataKit.ResetLocalKey( "MyGroup", "MyKey" );

DataKit.ResetAllLocalKeysInGroup(stringgroupName):voidResetsallexistingkeysinalocaldatagroup,maintainingtheiroriginalnames.Thisclearstheserializeddataandsetsthekeysasbeing'unassigned'.

DataKit.ResetAllLocalKeysInGroup( "MyGroup" );

DataKit.ResetAllLocalKeysInAllGroups():voidResetsallexistingkeysinalllocaldatagroups,maintainingtheiroriginalnames.

DataKit.ResetAllLocalKeysInAllGroups();

Page 60: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page60

DataKit.HasLocalGroup(stringgroupName):voidCheckstoseeifagroupexistsinlocaldata.

if( DataKit.HasLocalGroup( "MyGroup" ) ){ // Local Group Exists! }

DataKit.HasLocalKey(stringgroupName,stringkey):voidCheckstoseeifagroup/keyexistsinlocaldata.

if( DataKit.HasLocalKey( "MyGroup", "MyKey") ){ // Local Key Exists! }

DataKit.SetLocalKey<T>(stringgroupName,stringkey,TtoSerialize):voidSerializesanobjecttoaspecificlocalkeyusingthegroupNameandkey.

DataKit.SetLocalKey( "MyGroup", "MyVector3", new Vector3( 1f, 2f, 3f ) );

DataKit.SetLocalAsset<T>(stringgroupName,stringkey,TtoSerialize,stringformat,intquality=50):voidSavesasupportedreferenceasset(Texture2D,Audioclip,etc)byvaluesoitcanberecreatedatruntime.Ifusinganimage,makesuretouseeither"jpg"or"png"astheformat.IfusingtheJPGformat,youcanalsodefinethequalityasapercentage.Forothersupportedreferencetypes,settheformattoanemptystring.

DataKit.SetLocalKey( "MyGroup", "MyKey", myTexture2D, "jpg", 50 );

DataKit.GetLocalKey<T>(stringgroupName,stringkey):ReturnsTGetsanobjectfromaspecificlocalkeyusingthegroupNameandkey.Asthismethodusesgenerics,youmustsupplythedatatypebeforetheparameters.NOTE:Thiscanalsobeusedtoretrieveobjectssavedwiththe'SetLocalAsset'method.

Vector3 myVector3 = DataKit.GetLocalKey<Vector3>( "MyGroup", "MyVector3" );

DataKit.GetLocalKey<T>(stringgroupName,stringkey,TdefaultData):ReturnsTGetsanobjectfromaspecificlocalkeyusingthegroupnameandkey.Thethirdfieldwillbereturnedifthegroup/keydoesn'texist.NOTE:Thiscanalsobeusedtoretrieveobjectssavedwiththe'SetLocalAsset'method.

int myInt = DataKit.GetLocalKey<int>( "MyGroup", "myInt", 0 );

DataKit.RevertLocalDataGroup(stringgroupName):voidRevertsalocaldatagroupbacktotheoriginalsettingsoftheDataKitSetupinspector.Ifthegroupdidn'talreadyexist,thiswillbeignored.Ifthegroupwasdeletedinthecurrentlocaldata,itwillberecreated.

DataKit.RevertLocalDataGroup( "MyGroup" );

Page 61: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page61

DataKit.RevertLocalDataKey(stringgroupName,stringkey):voidRevertsalocaldatakeybacktotheoriginalsettingsoftheDataKitSetupinspector.Ifthegroup/keydidn'talreadyexist,Thiswillbeignored.Ifthegroup/keywasdeletedinthecurrentdata,itwillberecreated.

DataKit.RevertLocalDataKey( "MyGroup", "myInt" );

DataKit.RevertAllLocalData():voidRevertsalllocaldatabacktothedefaultsetupintheDataKitSetupinspector.

DataKit.RevertAllLocalData();

DataKit.RevertAllData():voidRevertsbothlocalandglobaldatabacktothedefaultsetupintheDataKitSetupinspector.

DataKit.RevertAllData();

DataKit.GetDefaultLocalDataKey<T>(stringgroupName,stringkey,TdefaultValue):ReturnsTAttemptstogetthedefaultvalueofalocalkey(thedefaultvalueusedinDataKitSetup,notthecurrentvalue).Ifthisvaluedidn'toriginallyexist,thedefaultvaluesenttothemethodwillbereturnedinstead.Thisissimilartorevertingdataexceptthecurrentvalueinlocaldataisunaffected.

int myInt = DataKit.GetDefaultLocalDataKey( "MyGroup", "myInt", 1 );

Page 62: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page62

Save File Methods Thefollowingisalistofmethodsforgettinginformationaboutthecurrentlyloadeddata:

DataKit.GetGlobalGameVersion():ReturnfloatGetsthegameversionthatwassavedinthecurrentlyloadedglobaldata.

float globalGameVersion = DataKit.GetGlobalGameVersion();

DataKit.GetLastGlobalDataFileSizeInBytes():ReturnlongGetsthegameversionthatwassavedinthecurrentlyloadedglobaldata.

long globalDataSizeInBytes = DataKit.GetLastGlobalDataFileSizeInBytes();

DataKit.GetGlobalDataDataKitVersion():ReturnfloatGetstheDataKitversionthatwassavedinthecurrentlyloadedglobaldata.

float globalDataKitVersion = DataKit.GetGlobalDataDataKitVersion();

DataKit.GetGlobalDataPlatform():ReturnstringGetstheplatformthatwassavedinthecurrentlyloadedglobaldata.

string globalDataKitPlatform = DataKit.GetGlobalDataPlatform();

DataKit.GetLocalGameVersion():ReturnfloatGetsthegameversionthatwassavedinthecurrentlyloadedlocaldata.

float globalGameVersion = DataKit.GetLocalGameVersion();

DataKit.GetLastLocalDataFileSizeInBytes():ReturnlongGetsthegameversionthatwassavedinthecurrentlyloadedlocaldata.

long localDataSizeInBytes = DataKit.GetLastLocalDataFileSizeInBytes();

DataKit.GetLocalDataDataKitVersion():ReturnfloatGetstheDataKitversionthatwassavedinthecurrentlyloadedlocaldata.

float localDataKitVersion = DataKit.GetLocalDataDataKitVersion();

DataKit.GetLocalDataPlatform():ReturnstringGetstheplatformthatwassavedinthecurrentlyloadedlocaldata.

string localDataKitPlatform = DataKit.GetDataPlatform();

Page 63: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page63

Serialized Data Methods IfyouneedaccesstoDataKit'srawdata,youcanusethefollowingmethods:

DataKit.GetSerializedDataFromGlobalKey(stringgroupName,stringkey):ReturnsstringGetsdatainitsrawformat(aserializedstring)fromaspecificglobalkey.

string myRawInt = DataKit.GetSerializedDataFromGlobalKey( "MyGroup", "myInt" );

DataKit.GetSerializedDataFromLocalKey(stringgroupName,stringkey):ReturnsstringGetsdatainitsrawformat(aserializedstring)fromaspecificlocalkey.

string myRawInt = DataKit.GetSerializedDataFromLocalKey( "MyGroup", "myInt" );

Page 64: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page64

Import / Export Data Methods IfyouneedDataKittoloadandsavedatatoandfromexternallocations(suchaswebservers),youcanusethefollowingmethodstohelp.ItshouldbenotedthatyourdatawillbeincompleteifyoualsouseExternalAssets.Ifyouneedtohandledatainthisway,donotuseExternalAssets.

DataKit.GetSerializedGlobalData(ActiononSuccess=null,ActiononFail=null):ReturnsstringSerializesthecurrentGlobaldataintoastringtobeusedforsavingelsewhere(suchaswebservers,etc).Ifthereisanerror,anemptystringwillbereturned.OptionalOnSuccessandOnFailcallbacks.

string mySerializedGlobalData = DataKit.GetSerializedGlobalData();

DataKit.SetSerializedGlobalData(stringserializedData,ActiononSuccess=null,ActiononFail=null):voidOverwritesthecurrentglobaldatausingaserializedstring.OptionalOnSuccessandOnFailcallbacks.

DataKit.SetSerializedGlobalData( mySerializedGlobalData );

DataKit.GetSerializedLocalData(stringsaveGameDescription="",ActiononSuccess=null,ActiononFail=null):ReturnsstringSerializesthecurrentlocaldataintoastringtobeusedforsavingelsewhere(suchaswebservers,etc).Onerror,anemptystringisreturned.Optionalsavegamedescriptionstring,OnSuccessandOnFailcallbacks.

string mySerializedLocalData = DataKit.GetSerializedLocalData();

DataKit.SetSerializedLocalData(stringserializedData,ActiononSuccess=null,ActiononFail=null):voidOverwritesthecurrentlocaldatausingaserializedstring.OptionalOnSuccessandOnFailcallbacks.

DataKit.SetSerializedLocalData( mySerializedLocalData );

DataKit.GetAllSerializedData(stringsaveGameDescription="",ActiononSuccess=null,ActiononFail=null):ReturnsstringSerializesthecurrentlocal&globaldataintoastringtobeusedforsavingelsewhere(suchaswebservers,etc).Onerror,anemptystringisreturned.YoucanprovideanoptionalsavegamedescriptionstringaswellasOnSuccessandOnFailcallbacks.

string mySerializedData = DataKit.GetAllSerializedData();

DataKit.SetAllSerializedData(stringserializedData,ActiononSuccess=null,ActiononFail=null):voidOverwritesthecurrentlocal&globaldatausingaserializedstring.OptionalOnSuccessandOnFailcallbacks.

DataKit.SetAllSerializedData( mySerializedData );

Page 65: DataKit - For Unity. · datakit for unity – page 6 datakit v2 upgrade guide important: do not upgrade from datakit v1.x if you have already released your game! datakit v2.0 cannot

DataKitforUnity–Page65

Support

Ifyouneedanyassistanceorhavesuggestionsforthisplugin,feelfreetovisitourwebsiteat:

www.unitygamesdevelopment.co.uk

Ihopeyoufindthissystemuseful,asIhaveinmyownpersonalprojects!=)

Allthebest!

-Mel