GUI Basicsand GUILayout Mode.docx
《GUI Basicsand GUILayout Mode.docx》由会员分享,可在线阅读,更多相关《GUI Basicsand GUILayout Mode.docx(12页珍藏版)》请在冰豆网上搜索。
GUIBasicsandGUILayoutMode
GUIBasics
Thissectionwillexplainthebarenecessitiesforscripting Controls with UnityGUI.
MakingControlswithUnityGUI
UnityGUIcontrolsmakeuseofaspecialfunctioncalled OnGUI().The OnGUI() functiongetscalledeveryframeaslongasthecontainingscriptisenabled-justlikethe Update() function.
GUIcontrolsthemselvesareverysimpleinstructure.Thisstructureisevidentinthefollowingexample.
/*Examplelevelloader*/
functionOnGUI(){
//Makeabackgroundbox
GUI.Box(Rect(10,10,100,90),"LoaderMenu");
//Makethefirstbutton.Ifitispressed,Application.Loadlevel
(1)willbeexecuted
if(GUI.Button(Rect(20,40,80,20),"Level1")){
Application.LoadLevel
(1);
}
//Makethesecondbutton.
if(GUI.Button(Rect(20,70,80,20),"Level2")){
Application.LoadLevel
(2);
}
}
Thisexampleisacomplete,functionallevelloader.Ifyoucopy/pastethisscriptandattachita GameObject,you'llseethefollowingmenuappearinwhenyouenter PlayMode:
TheLoaderMenucreatedbytheexamplecode
Let'stakealookatthedetailsoftheexamplecode:
ThefirstGUIline, GUI.Box(Rect(10,10,100,90),"LoaderMenu"); displaysa Box Controlwiththeheadertext"LoaderMenu".ItfollowsthetypicalGUIControldeclarationschemewhichwe'llexploremomentarily.
ThenextGUIlineisa Button Controldeclaration.NoticethatitisslightlydifferentfromtheBoxControldeclaration.Specifically,theentireButtondeclarationisplacedinsidean if statement.WhenthegameisrunningandtheButtonisclicked,this if statementreturnstrueandanycodeinsidethe if blockisexecuted.
Sincethe OnGUI() codegetscalledeveryframe,youdon'tneedtoexplicitlycreateordestroyGUIcontrols.ThelinethatdeclarestheControlisthesameonethatcreatesit.IfyouneedtodisplayControlsatspecifictimes,youcanuseanykindofscriptinglogictodoso.
/*Flashingbuttonexample*/
functionOnGUI(){
if(Time.time%2<1){
if(GUI.Button(Rect(10,10,200,20),"Meettheflashingbutton")){
print("Youclickedme!
");
}
}
}
Here, GUI.Button() onlygetscalledeveryothersecond,sothebuttonwillappearanddisappear.Naturally,theusercanonlyclickitwhenthebuttonisvisible.
Asyoucansee,youcanuseanydesiredlogictocontrolwhenGUIControlsaredisplayedandfunctional.NowwewillexplorethedetailsofeachControl'sdeclaration.
AnatomyofaControl
TherearethreekeypiecesofinformationrequiredwhendeclaringaGUIControl:
Type (Position, Content)
Observethatthisstructureisafunctionwithtwoarguments.We'llexplorethedetailsofthisstructurenow.
Type
Type isthe ControlType,andisdeclaredbycallingafunctioninUnity's GUIclass orthe GUILayoutclass,whichisdiscussedatlengthinthe LayoutModes sectionoftheGuide.Forexample, GUI.Label() willcreateanon-interactivelabel.Allthedifferentcontroltypesareexplainedlater,inthe Controls sectionoftheGuide.
Position
The Position isthefirstargumentinany GUI Controlfunction.Theargumentitselfisprovidedwitha Rect() function. Rect() definesfourproperties:
left-mostposition, top-mostposition, totalwidth, totalheight.Allofthesevaluesareprovidedin integers,whichcorrespondtopixelvalues.AllUnityGUIcontrolsworkin ScreenSpace,whichistheresolutionofthepublishedplayerinpixels.
Thecoordinatesystemistop-leftbased. Rect(10,20,300,100) definesaRectanglethatstartsatcoordinates:
0,20andendsatcoordinates310,120.Itisworthrepeatingthatthesecondpairofvaluesin Rect() aretotalwidthandheight,notthecoordinateswherethecontrolsend.Thisiswhytheexamplementionedaboveendsat310,120andnot300,100.
Youcanusethe Screen.width and Screen.height propertiestogetthetotaldimensionsofthescreenspaceavailableintheplayer.Thefollowingexamplemayhelpclarifyhowthisisdone:
/*Screen.width&Screen.heightexample*/
functionOnGUI(){
GUI.Box(Rect(0,0,100,50),"Top-left");
GUI.Box(Rect(Screen.width-100,0,100,50),"Top-right");
GUI.Box(Rect(0,Screen.height-50,100,50),"Bottom-left");
GUI.Box(Rect(Screen.width-100,Screen.height-50,100,50),"Bottom-right");
}
TheBoxespositionedbytheaboveexample
Content
ThesecondargumentforaGUIControlistheactualcontenttobedisplayedwiththeControl.MostoftenyouwillwanttodisplaysometextoranimageonyourControl.Todisplaytext,passastringastheContentargumentlikethis:
/*StringContentexample*/
functionOnGUI(){
GUI.Label(Rect(0,0,100,50),"ThisisthetextstringforaLabelControl");
}
Todisplayanimage,declarea Texture2D publicvariable,andpassthevariablenameasthecontentargumentlikethis:
/*Texture2DContentexample*/
varcontrolTexture:
Texture2D;
functionOnGUI(){
GUI.Label(Rect(0,0,100,50),controlTexture);
}
Hereisanexampleclosertoareal-worldscenario:
/*ButtonContentexamples*/
varicon:
Texture2D;
functionOnGUI(){
if(GUI.Button(Rect(10,10,100,50),icon)){
print("youclickedtheicon");
}
if(GUI.Button(Rect(10,70,100,20),"Thisistext")){
print("youclickedthetextbutton");
}
}
TheButtonscreatedbytheaboveexample
ThereisathirdoptionwhichallowsyoutodisplayimagesandtexttogetherinaGUIControl.Youcanprovidea GUIContent objectastheContentargument,anddefinethestringandimagetobedisplayedwithintheGUIContent.
/*UsingGUIContenttodisplayanimageandastring*/
varicon:
Texture2D;
functionOnGUI(){
GUI.Box(Rect(10,10,100,50),GUIContent("Thisistext",icon));
}
Youcanalsodefinea Tooltip intheGUIContent,anddisplayitelsewhereintheGUIwhenthemousehoversoverit.
/*UsingGUIContenttodisplayatooltip*/
functionOnGUI(){
//Thislinefeeds"Thisisthetooltip"intoGUI.tooltip
GUI.Button(Rect(10,10,100,20),GUIContent("Clickme","Thisisthetooltip"));
//ThislinereadsanddisplaysthecontentsofGUI.tooltip
GUI.Label(Rect(10,40,100,20),GUI.tooltip);
}
Ifyou'redaringyoucanalsouseGUIContenttodisplayastring,anicon,andatooltip!
/*UsingGUIContenttodisplayanimage,astring,andatooltip*/
varicon:
Texture2D;
functionOnGUI(){
GUI.Button(Rect(10,10,100,20),GUIContent("Clickme",icon,"Thisisthetooltip"));
GUI.Label(Rect(10,40,100,20),GUI.tooltip);
}
Thescriptingreferencepagefor GUIContent'sconstructor foranextensivelistofexamples.
LayoutModes
FixedLayoutvsAutomaticLayout
TherearetwodifferentmodesyoucanusetoarrangeandorganizeyourGUIs:
FixedandAutomatic.Upuntilnow,everyUnityGUIexampleprovidedinthisguidehasusedFixedLayout.TouseAutomaticLayout,write GUILayout insteadof GUI whencallingcontrolfunctions.YoudonothavetouseoneLayoutmodeovertheother,andyoucanusebothmodesatonceinthesame OnGUI() function.
FixedLayoutmakessensetousewhenyouhaveapre-designedinterfacetoworkfrom.AutomaticLayoutmakessensetousewhenyoudon'tknowhowmanyelementsyouneedupfront,ordon'twanttoworryabouthand-positioningeachControl.Forexample,ifyouarecreatinganumberofdifferentbuttonsbasedonSaveGamefiles,youdon'tknowexactlyhowmanybuttonswillbedrawn.InthiscaseAutomaticLayoutmightmakemoresense.Itisreallydependentonthedesignofyourgameandhowyouwanttopresentyourinterface.
TherearetwokeydifferenceswhenusingAutomaticLayout:
∙GUILayout isusedinsteadof GUI
∙No Rect() functionisrequiredforAutomaticLayoutControls
/*TwokeydifferenceswhenusingAutomaticLayout*/
functionOnGUI(){
//FixedLayout
GUI.Button(Rect(25,25,100,30),"IamaFixedLayoutButton");
//AutomaticLayout
GUILayout.Button("IamanAutomaticLayoutButton");
}
ArrangingControls
DependingonwhichLayoutModeyou'reusing,therearedifferenthooksforcontrollingwhereyourControlsarepositionedandhowtheyaregroupedtogether.InFixedLayout,youcanputdifferentControlsinto Groups.InAutomaticLayout,youcanputdifferentControlsinto Areas, HorizontalGroups,and VerticalGroups
FixedLayout-Groups
GroupsareaconventionavailableinFixedLayoutMode.TheyallowyoutodefineareasofthescreenthatcontainmultipleControls.YoudefinewhichControlsareinsideaGroupbyusingthe GUI.BeginGroup() and GUI.EndGroup() functions.AllControlsinsideaGroupwillbepositionedbasedontheGroup'stop-leftcornerinsteadofthescreen'stop-leftcorner.Thisway,ifyourepositionthegroupatruntime,therelativepositionsofallControlsinthegroupwillbemaintained.
Asanexample,it'sveryeasytocentermultipleControlson-screen.
/*CentermultipleControlsonthescreenusingGroups*/
functionOnGUI(){
//Makeagrouponthecenterofthescreen
GUI.BeginGroup(Rect(Screen.width/2-50,Screen.height/2-50,100,100));
//Allrectanglesarenowadjustedtothegroup.(0,0)isthetopleftcornerofthegroup.
//We'llmakeaboxsoyoucanseewherethegroupison-screen.
GUI.Box(Rect(0,0,100,100),"Groupishere");
GUI.Button(Rect(10,40,80,30),"Clickme");
//Endthegroupwestartedabove.Thisisveryimportanttoremember!
GUI.EndGroup();
}
Theaboveexamplecenterscontrolsregardlessofthescreenresolution
YoucanalsonestmultipleGroupsinsideeachother.Whenyoudothis,eachgrouphasitscontentsclippedtoitsparent'sspace.
/*UsingmultipleGroupstoclipthedisplayedContents*/
varbgImage:
Texture2D;//backgroundimagethatis256x32
varfgImage:
Texture2D;//foregroundimagethatis256x32
varplayerEnergy=1.0;//afloatbetween0.0and1.0
fun