GUI Basicsand GUILayout ModeWord格式文档下载.docx
《GUI Basicsand GUILayout ModeWord格式文档下载.docx》由会员分享,可在线阅读,更多相关《GUI Basicsand GUILayout ModeWord格式文档下载.docx(12页珍藏版)》请在冰豆网上搜索。
![GUI Basicsand GUILayout ModeWord格式文档下载.docx](https://file1.bdocx.com/fileroot1/2023-1/22/6f4d725a-eb10-4d78-9839-8377dfa7b14a/6f4d725a-eb10-4d78-9839-8377dfa7b14a1.gif)
)){
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),"
displaysa
Box
Controlwiththeheadertext"
.ItfollowsthetypicalGUIControldeclarationschemewhichwe'
llexploremomentarily.
ThenextGUIlineisa
Button
Controldeclaration.NoticethatitisslightlydifferentfromtheBoxControldeclaration.Specifically,theentireButtondeclarationisplacedinsidean
if
statement.WhenthegameisrunningandtheButtonisclicked,this
statementreturnstrueandanycodeinsidethe
blockisexecuted.
Sincethe
codegetscalledeveryframe,youdon'
tneedtoexplicitlycreateordestroyGUIcontrols.ThelinethatdeclarestheControlisthesameonethatcreatesit.IfyouneedtodisplayControlsatspecifictimes,youcanuseanykindofscriptinglogictodoso.
/*Flashingbuttonexample*/
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
isthe
ControlType,andisdeclaredbycallingafunctioninUnity'
s
GUIclass
orthe
GUILayoutclass,whichisdiscussedatlengthinthe
LayoutModes
sectionoftheGuide.Forexample,
GUI.Label()
willcreateanon-interactivelabel.Allthedifferentcontroltypesareexplainedlater,inthe
sectionoftheGuide.
Position
The
Position
isthefirstargumentinany
GUI
Controlfunction.Theargumentitselfisprovidedwitha
Rect()
function.
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
aretotalwidthandheight,notthecoordinateswherethecontrolsend.Thisiswhytheexamplementionedaboveendsat310,120andnot300,100.
Youcanusethe
Screen.width
and
Screen.height
propertiestogetthetotaldimensionsofthescreenspaceavailableintheplayer.Thefollowingexamplemayhelpclarifyhowthisisdone:
/*Screen.width&
Screen.heightexample*/
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*/
GUI.Label(Rect(0,0,100,50),"
ThisisthetextstringforaLabelControl"
Todisplayanimage,declarea
Texture2D
publicvariable,andpassthevariablenameasthecontentargumentlikethis:
/*Texture2DContentexample*/
varcontrolTexture:
Texture2D;
GUI.Label(Rect(0,0,100,50),controlTexture);
Hereisanexampleclosertoareal-worldscenario:
/*ButtonContentexamples*/
varicon:
if(GUI.Button(Rect(10,10,100,50),icon)){
print("
youclickedtheicon"
if(GUI.Button(Rect(10,70,100,20),"
Thisistext"
youclickedthetextbutton"
TheButtonscreatedbytheaboveexample
ThereisathirdoptionwhichallowsyoutodisplayimagesandtexttogetherinaGUIControl.Youcanprovidea
GUIContent
objectastheContentargument,anddefinethestringandimagetobedisplayedwithintheGUIContent.
/*UsingGUIContenttodisplayanimageandastring*/
GUI.Box(Rect(10,10,100,50),GUIContent("
icon));
Youcanalsodefinea
Tooltip
intheGUIContent,anddisplayitelsewhereintheGUIwhenthemousehoversoverit.
/*UsingGUIContenttodisplayatooltip*/
//Thislinefeeds"
Thisisthetooltip"
intoGUI.tooltip
GUI.Button(Rect(10,10,100,20),GUIContent("
Clickme"
"
));
//ThislinereadsanddisplaysthecontentsofGUI.tooltip
GUI.Label(Rect(10,40,100,20),GUI.tooltip);
Ifyou'
redaringyoucanalsouseGUIContenttodisplayastring,anicon,andatooltip!
/*UsingGUIContenttodisplayanimage,astring,andatooltip*/
icon,"
Thescriptingreferencepagefor
GUIContent'
sconstructor
foranextensivelistofexamples.
LayoutModes
FixedLayoutvsAutomaticLayout
TherearetwodifferentmodesyoucanusetoarrangeandorganizeyourGUIs:
FixedandAutomatic.Upuntilnow,everyUnityGUIexampleprovidedinthisguidehasusedFixedLayout.TouseAutomaticLayout,write
GUILayout
insteadof
whencallingcontrolfunctions.YoudonothavetouseoneLayoutmodeovertheother,andyoucanusebothmodesatonceinthesame
FixedLayoutmakessensetousewhenyouhaveapre-designedinterfacetoworkfrom.AutomaticLayoutmakessensetousewhenyoudon'
tknowhowmanyelementsyouneedupfront,ordon'
twanttoworryabouthand-positioningeachControl.Forexample,ifyouarecreatinganumberofdifferentbuttonsbasedonSaveGamefiles,youdon'
tknowexactlyhowmanybuttonswillbedrawn.InthiscaseAutomaticLayoutmightmakemoresense.Itisreallydependentonthedesignofyourgameandhowyouwanttopresentyourinterface.
TherearetwokeydifferenceswhenusingAutomaticLayout:
∙GUILayout
isusedinsteadof
GUI
∙No
functionisrequiredforAutomaticLayoutControls
/*TwokeydifferenceswhenusingAutomaticLayout*/
//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()
GUI.EndGroup()
functions.AllControlsinsideaGroupwillbepositionedbasedontheGroup'
stop-leftcornerinsteadofthescreen'
stop-leftcorner.Thisway,ifyourepositionthegroupatruntime,therelativepositionsofallControlsinthegroupwillbemaintained.
Asanexample,it'
sveryeasytocentermultipleControlson-screen.
/*CentermultipleControlsonthescreenusingGroups*/
//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),"
//Endthegroupwestartedabove.Thisisveryimportanttoremember!
GUI.EndGroup();
Theaboveexamplecenterscontrolsregardlessofthescreenresolution
YoucanalsonestmultipleGroupsinsideeachother.Whenyoudothis,eachgrouphasitscontentsclippedtoitsparent'
sspace.
/*UsingmultipleGroupstoclipthedisplayedContents*/
varbgImage:
//backgroundimagethatis256x32
varfgImage:
//foregroundimagethatis256x32
varplayerEnergy=1.0;
//afloatbetween0.0and1.0
fun