下载

1下载券

加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 Unity and MySQL

Unity and MySQL.pdf

Unity and MySQL

秸秆分解剂
2014-03-20 0人阅读 举报 0 0 暂无简介

简介:本文档为《Unity and MySQLpdf》,可适用于IT/计算机领域

Versions:UnityfMySQLAuthor:JonathanWoodAlias:ZumwaltDate:Updated:toincludeJScodeDocumentVersionUnityandMySQLTableofContentsUnityandMySQLNeededFilesServerConfigurationSettinguptheconnectionUserPermissionsDatabaseEditorTableCreationViewCreationUnityfUnityScriptingUnityCSharpScriptUnityJavascriptNeededFilesCommunityServerandWorkbenchwhichcanbeobtainedfrom:http:devmysqlcomdownloadsServerConfigurationOpentheserverandaddademouser:Simplymakethelogindemo,thepassworddemoandsettheconnectiontolocalhostandclickontheApplybuttonNowyouhaveademouserinthedefaultinstanceIfyouhavenodefaultinstance,justcreateonefromtheworkbenchonthelocalhostinstancethatisrunning,informationonhowtodothisiswithintheMySQLdocumentationSettinguptheconnectionOnthe“Home”tabinMySQLWorkbench,clickonthe“NewConnectioninthelowerleft,nametheconnectiondemo,changetheusertothedemouser:Wehavenotsetupaschemayetsowewilldothatnext,butfirstclickonthetestconnectionandenterthedemouserspasswordandclickon“OK”,ifyouhavesetupthedemousercorrectly,youshouldseethattheconnectionwascorrect,thewindowwillbeasfollowsUserPermissionsWenowhaveoneproblem,thedemouserisnotallowedtocreateschemasorhaveanyotherpermissionsoweneedtosetthoseforthatdemouserThisissimpletoset,clickbackonourAdmintabaslongasitstillisonyourworkbenchnexttotheHometab,ifnotthenyouhavetodoubleclickonthedatabaseinstanceunderServerAdministrationintheHometabYouwillseethelistofuserswhenyouclickontheAccountstabClickonthedemouserandthenyouwanttoclickontheAddEntrybuttonAtthispoint,thedemoschemamightnotshowupinthelist,butthatisok,simplychangetheHostselectiontoSelectedhostandchooselocalhostthenintheSchemablock,clickontheradialnexttoSchemasmatchingpatternornameandtypeindemothenclickonOKNowbackontheSchemaPrivilegestab,youwillseethatdemohasappearedandtheoptionsatthebottomareavailabletochoosepermissionsetsForthisdemo,youcansimplyclickontheSelectAll*button,youwillwanttoreviewthemanualonuserrightstounderstandwhateachpermissiondoes,onceyouhaveselectedallpermissionsviathatbutton,simplyclickontheSaveChangesbuttonOurdemousernowhastherightstocreateschemasinthedemodatabaseDatabaseEditorNowthatwehavethedemodatabasesetup,doubleclickonthedatabasewhichwillopenupourSQLEditorfortheDemodatabaseAtthemomentwehavenoschemas,sorightclickintheareaontheleftwheretheObjectBrowserwindowis,thenleftclickon“CreateSchema”GivethenameoftheschemademoandclickonApplyAscriptwindowwillappear,simplyclickonApplySQLSofarsogoodaslongasyouseethatthescriptwasexecutedsuccessfullybythefollowingexampleSimplyclickonFinishatthispointandcloseoutofthenewschemawindowifitisstillopenYounowhaveyourfirstdatabaseandyouarereadytoaddatablethatwillbeusedfortheUnitydemo,wearegoingtodealwithonlyasingletableandasingleviewinthisexampleSo,letusbeginthatprocessTableCreationTostartout,onourSQLEditorforthedemoschema,wehavetheabilitytoaddtablesbysimplyclickontheAddTablebuttonwithinthedemoSchemaOnceyoudoubleclickontheAddTablebutton,anewtablewindowwillappearWewillsimplykeepthingsmovingalongbynamingthistabledemotablewithgivingitaCommentofUnityDemoTableontheTabletabasfollows:Movingalong,weneedtoaddsomecolumnstoourtable,soclickontheColumnstabalongthebottomofthenewtablewindowWewanttokeepthetableID,thisisimportantforindexingreasonsandmanyotherreasonsbeyondthescopeofthisdocument,soleavethefirstcolumnaloneToaddinanewcolumn,doubleclickinthecelldirectlybeneaththeiddemotableandthefieldwillbecomeeditableWewanttocreatethefollowingcolumnsforthisdemo:(seeimage)Thisisreallystraightforward,NNmeansnotandPKmeansprimarykey,refertotheMySQLmanualforeachselectabletypeandalsotheDatatypes,fornowwewillnotworryaboutanyotheroptionshereexceptmakingsurethatiddemotableissetwithAIwhichisautoincrementOnceyouhavecreatedthattable,simplyclickonApplyThiswillbringupaSQLScripttoDatabasewindowforyoutoverifyhowthescriptwillexecute,justassumeitisrightaslongasthefieldsshowandclickonApplySQL,Ifallwentwell,youwillhaveasuccesswindow,sosimplyclickonFinishNowyouwillbebackatthenewtablewindowwhereyoucannowsimplyclickontheClosebutton,youshouldbebackattheMySQLWorkbenchandyoushouldseethatthedemotableexistsViewCreationNowwehaveatableofdemotableandwewanttocreateaview,althoughyoucouldavoidtheviewanddoselectqueriesdirectlyagainstthetable,youwanttogetintopracticeofusingviewsforselectqueriesandleavetheinsertupdatedeletecommandstothetabledirectinsteadBesttostudyuponwhytodothisthroughtheunderstandingofdatabaseusewhichisbeyondthescopeofthisdocumentJustlikethetablecreation,ontheMySQLWorkbench,thereisasectionthathasabuttonforAddViewandjustlikethetable,youdoubleclickontheAddViewtobeginthecreationprocessThisisalittletrickierbuttokeepthissimple,thequerytextyouwantisasfollows:CREATEVIEW`demo``viewdemo`ASSELECT*FROMdemotableOnceyouhavethattextinthequeryeditor,clickontheApplybutton:Averifywindowwillappeartoshowyouthesyntax,soclickonApplySQLAslongasyouhavenoscripterrors,thesuccesswindowwillappear,soclickontheFinishbuttonAlthoughtheDDLstringhasnowchangedinthenewviewwindow,donotworryaboutthatfornow,simplyclickontheClosebuttonNow,backonourSQLEditor(demo)window,wehaveademotableandaviewdemo!UnityfPresumingyouareusingUnitywithversionf,youwillwanttohaveseveralfilesinyourAssetsfolderforthistoworkYouneedtheMysqldatadllandtheSystemDatadllfiles,bothofwhichareinthethreadsontheUnitysite:http:forumunitydcomthreadsConnectiontoMySQLDBmysqlclientdllIfforsomereasonthefilesarenolongerinthatthread,thenyoucanlocateacopyofthemonyourlocalinstallationofUnitywithintheEditorfolder,therearesubfoldersandyoucansearchthroughthemforanupdatedcopyofthosefilesNow,tobeginwith,weneedabrandnewblankproject,soopenUnity,createanewprojectandstoreitinafoldercalledMySQLDemoandclickonCreate:(optionallyyoucanuseanexistingprojectifyouwant)Wewanttokeepthisthingclean,solet’sputourneededlibrariesintoafolderthatwewillcreateandcallthatfolderLibraries,simplyclickontheCreateundertheProjecttab,chooseFolderthenrenametheNewFoldertoLibraries,youcanclickontheNewFoldersothatitishighlightedandhittheFfunctionkeythentypeinthenameLibrariesandhitEnter,theendresultthatwearelookingforisasfollows:Ourcurrentworkbenchscenehasnotbeensavedyet,soletusgoaheadandsavethesceneandprojectClickonFilethenSaveScene,settheFilenametoDemoandclicksave,nowwewillhaveaDemosceneintheProject,youwanttogetintothehabitearlyonwithsavingyourworkasyoumovethroughitandyouwillalsowanttogetintothehabitofbackingupyourworkjustincasesomethinggoeshorriblywrongNowwearereadytodragourfilesintotheLibrariesfolder,locatewhereyouhavesavedyourneededDLL’sanddragthemintotheLibrariesfolderOnceyouhavesuccessfullydonethis,Unitywillthendoaquickimportandreadthelibrariesthentheywillshowupinthehierarchyasfollows:Wenowhaveourscene,wehaveourlibraries,nowweneedtothrowsomerandomitemsintothescene,keepitsimple,andaddaplane,acubeandaspherehoweveryoulikeYouusetheScenetabandthenthemenuitemforGameObject>CreateOtherthenyoucanselectthePlane,repeatfortheCubeandonceagainfortheSphere,movethemaroundabit,seetheUnitymanualoncreatingprimitivesandusingtheUIOnceyouhavethosecreated,savethescenesothatyouaresavedinyourcurrentworkingstateFinalstephereisthatweneedtocreatesomewayforthesystemtoknowwhatwewanttoallowtobesavedandwhatwedonotTheeasiestwaytoaccomplishthistaskistocreateanewtagwiththevalueof“Savable”Simplyclickonthecubeobject,andthenclickonthedropdownforTagthenclickon“AddTag”WewillmakeElementcalled“Savable”Anyobjectthatwewanttohavesaved,wewillsetittothatTagMakesuretochangetheSphereandCubeTagtotheSavablebeforeyoucontinuethiswaywhenweusethe“Save”button,itwillsavethevaluesoftheCubeandSphere’spositionandrotationtothedatabaseLet’snowmoveontoscriptingsowecansavethedataaboutthisscenetothedatabaseUnityScriptingRememberbackwhenwecreatedourSchema,wehadafewcolumnswecreatedThisisthedataweneedtocollectandsendorretrievefromMySQLKeepingwiththethemeofkeepingthingssimple,wewillonlycreatescriptfileandcallthatscriptfileMySQL,youcanchooseeitherJavaScriptorC#scriptwhencreatingitClickonCreateundertheProjecttabthenclickonthescripttypeyouwanttoworkwith,again,eitherCSharpScriptorJavascript,nowyouwillwanttorenamethatscriptfileyoujustcreated,soclickonitsothatitishighlightedandhittheFfunctionkeyandrenamethescripttoMySQLandhitenterForthisexampleIhavecreatedscriptssoIcanshowthecodeforeitherC#orJS,youonlyneedandcallitMySQLNowitistimetopopulatethecode…UnityCSharpScriptDoubleclickontheMySQLscriptthatyoujustcreatedthiswillthenopeninyourfavoritescripteditingprogram!(SeeUnitymanualonhowtochangetheeditorpreferences,forC#IuseVS)OnemajordifferencebetweenC#andJavascript,isthatC#usesClassesandyouhavetomakesureyourclassmatchesthefilename,thisisamust,seetheUnitymanualonwhyBEGINCODESNIPPETFORC#usingUnityEngineusingMySqlDatausingMySqlDataMySqlClientusingSystemusingSystemDatausingSystemCollectionsusingSystemCollectionsGenericpublicclassMySQLCS:MonoBehaviour{Intruth,theonlythingsyouwanttosavetothedatabasearedynamicobjectsstaticobjectsinthescenewillalwaysexist,somakesuretosetyourTagbasedonthedocumentationforthisdemovaluestomatchthedatabasecolumnsstringID,Name,levelname,objectTypefloatposx,posy,posz,tranx,trany,tranzboolsaving=falseboolloading=falseMySQLinstancespecificitemsstringconstr="Server=localhostDatabase=demoUserID=demoPassword=demoPooling=true"connectionobjectMySqlConnectioncon=commandobjectMySqlCommandcmd=readerobjectMySqlDataReaderrdr=errorobjectMySqlErrorer=objectcollectionarrayGameObjectbodiesobjectdefinitionspublicstructdata{publicintUIDpublicstringID,Name,levelname,objectTypepublicfloatposx,posy,posz,tranx,trany,tranz}collectioncontainerList<data>GameItemsvoidAwake(){try{setuptheconnectionelementcon=newMySqlConnection(constr)letsseeifwecanopentheconnectionconOpen()DebugLog("ConnectionState:"conState)}catch(Exceptionex){DebugLog(exToString())}}voidOnApplicationQuit(){DebugLog("killingcon")if(con!=){if(conState!=ConnectionStateClosed)conClose()conDispose()}}UsethisforinitializationvoidStart(){}UpdateiscalledonceperframevoidUpdate(){}guieventlikeabutton,etcvoidOnGUI(){if(GUIButton(newRect(,,,),"Save")!saving){saving=truefirstletscleanoutthedatabaeDeleteEntries()nowletssavethesceneinformationInsertEntries()youcouldalsousetheupdateifyouknowtheIDoftheitemalreadysavedsaving=false}if(GUIButton(newRect(,,,),"Load")!loading){loading=trueletsreadtheitemsfromthedatabaseReadEntries()nowdisplaywhatisknownaboutthemtoourlogLogGameItems()loading=false}}InsertnewentriesintothetablevoidInsertEntries(){prepData()stringquery=stringEmptyErrortrappinginthesimplestformtry{query="INSERTINTOdemotable(ID,Name,levelname,objectType,posx,posy,posz,tranx,trany,tranz)VALUES(ID,Name,levelname,objectType,posx,posy,posz,tranx,trany,tranz)"if(conState!=ConnectionStateOpen)conOpen()using(con){foreach(dataitminGameItems){using(cmd=newMySqlCommand(query,con)){MySqlParameteroParam=cmdParametersAdd("ID",MySqlDbTypeVarChar)oParamValue=itmIDMySqlParameteroParam=cmdParametersAdd("Name",MySqlDbTypeVarChar)oParamValue=itmNameMySqlParameteroParam=cmdParametersAdd("levelname",MySqlDbTypeVarChar)oParamValue=itmlevelnameMySqlParameteroParam=cmdParametersAdd("objectType",MySqlDbTypeVarChar)oParamValue=itmobjectTypeMySqlParameteroParam=cmdParametersAdd("posx",MySqlDbTypeFloat)oParamValue=itmposxMySqlParameteroParam=cmdParametersAdd("posy",MySqlDbTypeFloat)oParamValue=itmposyMySqlParameteroParam=cmdParametersAdd("posz",MySqlDbTypeFloat)oParamValue=itmposzMySqlParameteroParam=cmdParametersAdd("tranx",MySqlDbTypeFloat)oParamValue=itmtranxMySqlParameteroParam=cmdParametersAdd("trany",MySqlDbTypeFloat)oParamValue=itmtranyMySqlParameteroParam=cmdParametersAdd("tranz",MySqlDbTypeFloat)oParamValue=itmtranzcmdExecuteNonQuery()}}}}catch(Exceptionex){DebugLog(exToString())}finally{}}UpdateexistingentriesinthetablebasedontheiddemotablevoidUpdateEntries(){prepData()stringquery=stringEmptyErrortrappinginthesimplestformtry{query="UPDATEdemotableSETID=ID,Name=Name,levelname=levelname,objectType=objectType,posx=posx,posy=posy,posz=posz,tranx=tranx,trany=trany,tranz=tranzWHEREiddemotable=UID"if(conState!=ConnectionStateOpen)conOpen()using(con){foreach(dataitminGameItems){using(cmd=newMySqlCommand(query,con)){MySqlParameteroParam=cmdParametersAdd("ID",MySqlDbTypeVarChar)oParamValue=itmIDMySqlParameteroParam=cmdParametersAdd("Name",MySqlDbTypeVarChar)oParamValue=itmNameMySqlParameteroParam=cmdParametersAdd("levelname",MySqlDbTypeVarChar)oParamValue=itmlevelnameMySqlParameteroParam=cmdParametersAdd("objectType",MySqlDbTypeVarChar)oParamValue=itmobjectTypeMySqlParameteroParam=cmdParametersAdd("posx",MySqlDbTypeFloat)oParamValue=itmposxMySqlParameteroParam=cmdParametersAdd("posy",MySqlDbTypeFloat)oParamValue=itmposyMySqlParameteroParam=cmdParametersAdd("posz",MySqlDbTypeFloat)oParamValue=itmposzMySqlParameteroParam=cmdParametersAdd("tranx",MySqlDbTypeFloat)o

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

文档小程序码

使用微信“扫一扫”扫码寻找文档

1

打开微信

2

扫描小程序码

3

发布寻找信息

4

等待寻找结果

我知道了
评分:

/30

Unity and MySQL

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利