Sie sind auf Seite 1von 42

10/10/2014

GustavoPatow
IMAE UdG

Introduction
Unityisacrossplatformgamecreationsystem
developedbyUnityTechnologies,includinga
gameengineandintegrateddevelopment
environment(IDE)
Itisusedtodevelopvideogamesforwebsites,
desktopplatforms,consoles,andmobiledevices
FirstannouncedonlyforMacOS,atApples
WorldwideDevelopersConferencein2005,ithas
sincebeenextendedtotargetmorethanfifteen
platforms
Itisnowthedefaultsoftwaredevelopmentkit
(SDK)fortheNintendoWiiU

10/10/2014

What is Unity?
Unity1launchedonstageatApplesWorldwideDevelopersConference 2005
byDavidHelgason,NicholasFrancis,andJoachimAnte.

WhatisUnity
Free*multiplatform(game)developmenttool

Setupscenesvisually
AttachcomponentstoGameobjects
Logicinscripts(MonoC#,Javascript orBoo)
Integratedphysics(PhysX),RakNet
(networking),soundetc...
Multiplatform,includingwebplayer

Unity3Dusesalefthandedcoordinatesystem

10/10/2014

WheretoGet..
Tutorial
http://unity3d.com/learn
Download
http://unity3d.com/unity/download

Workflow
Unityispowerful,completegamedevelopment
system
Create3Dobjects/scenesinUnity
Orimportobjectscreatedin3Dmodelling
packages
Usescriptingtocontrolanimations/scene
changesetc.
Exporttostandalonegame,orwebpage
component,ormobileapp

10/10/2014

Main interface

Unityactuallyistheunionof
(1)a gameengine,thatallowsgamecreated
torun(hencetobeplayed)indifferent
environments,
(2)anapplicationwherethevisiblepiecesof
agamecanbeputtogether(the IDE)witha
graphicalpreviewandusingacontrolledplay
itfunction,and
(3)a codeeditor

10/10/2014

Scripting

Thegameengine'sscriptingisbuilton Mono,the
opensourceimplementationofthe .NET
Framework.Programmerscanuse:
UnityScript (acustomlanguagewith syntax,
referredtoas JavaScript bythesoftware)
C#
Boo (whichhasa Pythoninspiredsyntax)

Rendering
Unitysupportsartassetsandfileformatsfrom 3ds
Max, Maya, Blender, AdobePhotoshopandothergraphicsprograms.
Theseassetscanbeaddedtothegameproject,andmanagedthroughUnity's
graphicaluserinterface.

10/10/2014

Physics
Unityalsohasbuiltinsupport
for Nvidia's (formerlyAgeia's) PhysX physics.

Animation
Theretargetingrigcanbesetuponyourcharacterwithjusta
fewmouseclicksusingautomaticbonemappingandstance
posecomputingalgorithms.Therigbreaksdownbodymotion
intoasetofmusclecontractionsandusesamassmodelto
computebodymasscenterandaveragebodyorientationfor
motiontrajectory.

10/10/2014

2D & 3D
AllscenesinUnityare3D,with2Dgamesrenderedusingflatplanes.This
meansitsincrediblyeasytocombine3Dand2Delements.Simplyswitch
yourSceneviewbetween2Dand3DandmakeuseofPerspectiveand
Orthographiccameras.

Multiplatform
Unitysupportsdeploymenttomultiple
platforms.Withinaproject,developers
havecontroloverdeliverytomobile
devices,webbrowsers,desktops,and
consoles.

10/10/2014

AmongtheSleep
ByKrillbite Studio

MonumentValley
Byustwo

BySquareEnix

USERINTERFACE

10/10/2014

Unity maininterfacecomponents

UnityInterface
LearningtheInterface
TheMainEditorWindowismadeupof
severalTabbedWindows,calledViews
ProjectBrowser ,Hierarchy ,Toolbar ,SceneView
GameView ,Inspector ,OtherViews

10/10/2014

Unity maininterfacecomponents
Preview/Play

TransformTools

Inspector

Scene

Hierarchy

Project(Assets)

UnityInterface
ProjectBrowser
accessandmanagetheassetsthatbelongto
yourproject

10

10/10/2014

UnityInterface
Hierarchy
containseveryGameObject inthecurrentScene
Parenting
TomakeanyGameObject thechildofanother,dragthe
desiredchildontothedesiredparentintheHierarchy.
Achildwillinheritthemovementandrotationofitsparent.

Two unparented objects

One object parented to another

UnityInterface
Toolbar
TheToolbarconsistsoffivebasiccontrols.
EachrelatetodifferentpartsoftheEditor.
Transform Tools : used with the Scene View
Transform Gizmo Toggles : affect the Scene View display
Play/Pause/Step Buttons : used with the Game View
Layers Drop-down : controls which objects are displayed in Scene
View
Layout Drop-down : controls arrangement of all Views

11

10/10/2014

UnityInterface
SceneView
usetheSceneViewtoselectandpositionenvironments,
theplayer,thecamera,enemies,andallother
GameObjects
SceneViewNavigation
MovearoundontheX/Zplane:Usethearrowkeys
Flythroughmode
Holdtherightmousebutton
ThisturnsyourmouseandWASDkeys(plusQandEforupanddown)
intoquickfirstpersonviewnavigation

Orbitthecameraaroundthecurrentpivotpoint
HoldAltandleftclickdrag

DragtheSceneViewcameraaround
HoldAltandmiddleclickdrag

ZoomtheSceneView
HoldAltandrightclickdrag

UnityInterface
SceneView
SceneGizmo
displaystheSceneCamera'scurrentorientation
allowsyoutoquicklymodifytheviewingangle
Eachofthecolored"arms"ofthegizmo
representsageometricaxis
Clickonthetextunderneaththegizmotoswitch
betweenthenormalperspective viewandan
isometric view

12

10/10/2014

UnityInterface
SceneView
PositioningGameObjects
Focusing
SelectanyGameObjectandpresstheFkey

Translate,Rotate,andScale
usetheTransformToolsintheToolbartoTranslate,
Rotate,andScaleindividualGameObjects

UnityInterface
GameView
Representativeofyourfinal,publishedgame
PlayMode
UsethebuttonsintheToolbartocontrolthe
EditorPlayModeandseehowyourpublished
gamewillplay

GameViewControlBar

13

10/10/2014

UnityInterface
Inspector
displaysdetailedinformationabout
yourcurrentlyselectedGameObject,
includingallattachedComponents
(morelateron)andtheirproperties

Modeling

Texture

Sound

UnityInterface
OtherViews
TheConsole showslogsofmessages,warnings,and
errors.
TheAnimationViewcanbeusedtoanimateobjects
inthescene.
TheProfiler canbeusedtoinvestigateandfindthe
performancebottlenecksinyourgame.
TheAssetServerView canbeusedtomanageversion
controloftheprojectusingUnity'sAssetServer.
TheLightmappingView canbeusedtomanage
lightmapsusingUnity'sbuiltinlightmapping.
TheOcclusionCullingView canbeusedtomanage
OcclusionCullingforimprovedperformance.

14

10/10/2014

CustomizingYourWorkspace
CustomizingYourWorkspace
customizeyourLayoutofViewsbyclick
draggingtheTabofanyViewtooneofseveral
locations

STRUCTURE

15

10/10/2014

Projects

Acompletegame
Containsalltheelementsofthegame
Canholdmanyscenes
Haveassetsaslibrariestobuildgames

Scenes

Asinglescenecanhaveonegamelevel
Noteverysceneisnecessaryagamelevel
HoldstheHUD(HeadUpDisplay)
Havegameoverorcutsequences
Iscomposedofmanygameobjects

16

10/10/2014

GameObjects
A"thing"inthegame
thecurrentLevel'sground
theplayer
enemies
healthpickups
triggerpoint

Components
Arethebuildingblocks
ofGameObjects
Theycanrepresent
Visibleentities
Abstractentities

Multiplecomponents
canbeattachedtoa
GameObject

Component

Components
have variables

Meshes

Materials

Cameras

Terrain
Data

Particle
Systems

Lights

Visible Entities

Abstract Entities

17

10/10/2014

GameObjects,cont.
[Createanemptygameobject]
Composedofcomponents
Transform(ascenenode)

AllGameObjects havethis.
Scale,Rotation,Translation
fromparentnode
Thehierarchypaneisreallyascenegraph

MeshFilter/MeshRenderer
Physics
Collider(capsule,box,mesh,)
RigidBody

GameObjects,cont.

ParticleEmitter
GUITexture /GUIText
AudioSource (2Dor3D,dependingonasset)

Script(foranythingelse)

TagsandLayers
Layers:
Selectiverendering,selectivehitdetection
Abitmask(32bitinteger)
e.g."Ground","Postprocessing"

Tag:

Usefulmainlyinscripting
Alsoa32bitinteger
A"group"(fastFindWithTag methods)
e.g."MainCamera","Player","Pickup","Exit"

18

10/10/2014

Assets
AreintheUIprojectpane
Canbeanything:Materials,Textures,
Meshes,Scripts,Audiofiles,Prefabricated
GameObjects,AssociatedAnimations,
etc.
HelptoreuseGameObjectsandbuild
ScenesintheHierarchyPane

ConceptualFramework
Components

S
c
r
ip
t
Assets

Game Object

Assets
Assets

Game Object
Scene

Unity Project

19

10/10/2014

Prefabs
Anelementofanassetdefinedas
template
WorksasaninstanceofaGameObjectfor
moreefficientmemorymanagement
AnychangeinaPrefabaffectsallthe
instances
Itispossibletoadjustindividualsettings
toeachPrefab

Prefabs
Assets=>Create=>Prefab
ChooseAssets>Create>Prefabfromthemenubarandname
yournewPrefab.
InHierarchyView,selecttheGameObject youwishtomakeinto
aPrefab.
Drag&droptheGameObject fromtheHierarchyontothenew
PrefabinProjectView.
TheGameObject's namewillturnbluetoshowthatitisa
Prefab.
Ifyouchangetheprefabdefinition,allinstanceswillchangetoo.

Youcanmodifythevaluesofcomponentattributes,butnot
the"structure"(e.g.components,althoughyoucandisable
them)
Youcan"break"the
prefabconnectionby
GameObject=>BreakPrefabInstance.

20

10/10/2014

SCRIPTING

Scripts(UnityScript)

UnityScript isbasicallyJavaScript
Otherchoices:C#,Boo
Assets=>Create=>JavaScript
DoubleclicktogointoMonoDevelop
Twofunctionsaddautomatically:StartandUpdate
Example(inUpdate)
transform.Rotate(0,5,0);

Debugoutput
print("Hey!"+tempVar);
Displayatbottomofwindow,orintheoutput
window.

21

10/10/2014

Scripts,cont.
Variabledeclaration
public var myVar [: myType] [= myVal];
public var direction : int = 99;

Othermodifiers:
static:visibletootherscripts
private:can'tbemodifiedinInspector.

BasicTypes:int,float,string,boolean
Enumerations:
enum myEnum {state1,state2};
publicvar myState =myEnum.state1;

Scripts,cont.
Classes
Foo.js
CreatesaclassnamedFoo
VariablesinFoo.jsaremembers,functionsare
methods.

Otherway:
class MyRecord extends XYZ
{
public var name: integer;
function doSomething() { /**/ }
};

22

10/10/2014

Scripts,cont.
PublicVariablesarevisible(and
changeable)intheInspector
Agreatfeature!
Note:youcanchangethematruntime(but
it'snotpermanent)

Classes,cont.
Classmusthavesamenameas.js file(casesensitive)
ToaddascripttoaGameObject,derivefrom
MonoBehavior
Constructor(functionwithsamenameasclass)seemsto
becalled:
beforeStartmethodiscalled
When(re)enteringPlayer(afterpressingstop)

Youseemtobeabletoreference(other)scripts
anywhereintheproject.

23

10/10/2014

Classes,cont.
Someotherimportantmethods/functionsto
overload:

FullList:http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.html
LateUpdate:CalledafterallUpdate's
OnMouseEnter [GUIElement's]
OnCollisionEnter
Calledwhenthiscollidercollideswhenanother
Note:onecollidermusthaveanonkinematicrigidbody

OnCollisionStay

Accessingcomponents
Thegameobjectmostlikelyhasother
componentsattachedtoit.
E.g.Youhavea"Transform"componentin
Inspector
Accessitinscriptlike:
"transform.position.x"

Notelowercase(thisistherule)

24

10/10/2014

Messages
Format
GameObject.SendMessage(string, param);
var go = GameObject.Find("Mine4087");
go.SendMessage("explode", 14.3);
// (In any script(s) attached to Mine4087)
function explode(timer : float)
{
//
}

ThereisalsoaBroadcastMessage
Similarstructure.Issenttoallchild
GameObjects recursively.

ScriptingMisc.
Time.deltaTime //TimesincelastUpdate.
Application.LoadLevel(x)
xisanintegerorstring
Removesallotherobjects,unless

DontDestroyOnLoad(gameObject);
KeepsitfrombeingdestroyedonLoadLevel call

25

10/10/2014

Scriptlifecycle
Game
Begin

During
Game

Destroy
is called

Awake()

Update()

OnDestroy()

+Is like the


constructor of a
GameObject
+Initialize variables
+Executed only
one time

Called every frame

LateUpdate()

+When other
GameObject script
calls to destroy an
object you can
finalize variables

Called every frame

Start()
Game
End

Inter object
initialization

Classdiagram

26

10/10/2014

FINALREMARKS

GUI
MadeofGameObject's
AddaGUILayer componentto(a)camera.
Makemorecomponentsforeachelement
MakethemchildrentotheGUIlayer
component.

Position:
(0,0,z):bottomleft
(1,1,z):topright

27

10/10/2014

Conclusion
Soonceyouhavethegamedesignandallthe
requiredskills
youcanputtogethergraphics,sounds,animations
inUnitysIDE,
writeintheeditorthecodeassociatedtothe
assets
andthengenerateaplayableapplicationthatruns
inseveraldifferentenvironments,
asoneofthefeaturesofUnityisthatitismulti
platform,thatismoreorlessthesamegamecanrun
similarlyonaniPadoronWindows.

BecauseofthesefeaturesUnityisapopular
gameengineinvideogamedevelopment.

References
http://wikipedia.org/wiki/Unity_(game_engine)
http://unity3d.com
http://forum.unity3d.com
http://designagame.eu

28

10/10/2014

EXAMPLE:AFIRSTGAME

YourFirstGame
Project:RollaBall
Createasimplerollingballgamethatteaches
youmanyoftheprinciplesofworkingwith
GameObjects,Components,Prefabs,Physics
andScripting

29

10/10/2014

YourFirstGame
Project:RollaBall
100.Introduction
101.Settingupthegame
102.Movingtheplayer
103.Movingthecamera
104.Creatingpickupobjects
105.Collectingandcounting
106.Displayingtext
107.Publishingthegame

Settingupthegame
Settingupthegame

Scale X 2, Y 1, Z 2

FileMenu NewProject
Rollaball
SaveScene(Ctrl+S)
Create NewFolder_Scene
SaveasMiniGame.unity

CreateGameObjectPlane
UsingMenu
GameObject CreateOther Plane

UsingHierarchyWindow
CreateTab Plane

RenameGround
SelectGearMenuinInspectorView Reset
Focusing:SelectGameObjectGround
Edit FrameSeleceted ||FKey

30

10/10/2014

Settingupthegame
Settingupthegame
CreateGameObjectSphere
GameObject inMainMenu CreateOther
Sphere
RenamePlayer&Reset
SelectGearMenuinInspectorView Reset
FocusingGameObjectPlayer(FKey)
ChangePositionY 0.5

Scene View

Game View

Settingupthegame
AddDirectionalLight
CreateTabinHierarchyView DirectionalLight
RenameMainLight&Reset
ChangeTransforminInspectorView
RotationX 30,Y 60

ShadowType:SoftShadow
Resolution:VeryHighResolution

DuplicateMainLight
RenameFillLight&Reset
ChangeTransforminInspectorView
RotationX 30,Y 60

ChangeColor&Intensity 0.1
TurnoffShadow

31

10/10/2014

Settingupthegame
OrganizingHierarchy
CreateEmptyGameObject CreateEmpty
RenameLighting&ResettoTheOrigin
DragMainLight&FillLightintoLighting
ChangeYPosition 100

Movingtheplayer
Movingtheplayer
Movingtheplayerobjectusingplayerinputand
physicsforces.
SelectPlayer&AddComponentPhysics
1.
2.

UsingMainMenu:Component Physics Rigidbody


UsingInspector:PressButtonAddComponent

MakingScripts

CreateNewFolderinProjectView
RenameScripts
CreateC#Scripts
1.
2.
3.

Assets Create C#Scripts(MainMenu)


Create C#ScriptsinProjectView
SelectPlayer AddComponent NewScripts
RenamePlayerController

32

10/10/2014

Movingtheplayer
OpenMonoDevelop
SelectPlayerController&PressOpenButtonin
Inspector
Writtenbelowcode&Build

Movingtheplayer
Update()
CalledEveryFrame
Usedforregularupdatessuchas
MovingNonPhysicsobjects,SimpleTimers,ReceivingInput

Updateintervaltimevary

FixedUpdate()
Called EveryPhysicsStep
FixedUpdateintervalareconsistent
Usedforregularupdatessuchas
AdjustingPhysics(Rigidbody)objects

LateUpdate
Calledonceperframe,afterUpdate()hasfinished
Usedforafollowingcamera

33

10/10/2014

Movingtheplayer
OpenMonoDevelop
UsingHelp(Ctrl+')

Movingtheplayer
ReturntoUnityEditor
InputManager
EditProject SettingsInput menu

Play(Ctrl+P)
Usekeyboardw,s,a,d

ChangeScriptCode&Play
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed;
void FixedUpdate() {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.AddForce(movement*speed*Time.deltaTime);
}
}
deltaTime : The time in seconds it took to complete the last frame

34

10/10/2014

Movingthecamera
Movingthecamera
SelectMainCamera&ChangeTransform
PositionY10,RotationX45

MakeMainCameraasChildofPlayer
Move&RotatePlayer
But,PlayGame NoGood
Camerafollowtheballwithrotation

DetachMainCamera

Movingthecamera
CreateNewscriptCameraController
AddComponenttoMainCamera
OpenMonDevelop &EditCameraController
AssignPlayer

PlayTheGame
Camerafollowtheballwithoutrotation
usingUnityEngine;
usingSystem.Collections;
publicclassCameraController :MonoBehaviour {
publicGameObject Player;
privateVector3offset;
//Usethisforinitialization
voidStart(){
offset=transform.position;
}
voidLateUpdate (){
transform.position =Player.transform.position +offset;
}
}

35

10/10/2014

Creatingpickupobjects
Creatingpickupobjects
Settinguptheplayareaandcreatingpickupobjects.
MakingWalls
CreateEmptyWalls&ResetTransform
CreateNewCubeWestWall
MoveWestWallintoWalls
ChangeScale:X0.5,Y2,Z20.5,Translate:X10

DuplicateWestWall EastWall
ChangeTranslate:X10

DuplicateWestWall NorthWall
Scale:X20.5,Y2,Z0.5,Translate:Z10

DuplicateNorthWall SouthWall
Translate:Z10

Creatingpickupobjects
CreatePickups
CreateNewCubePickUp&Reset
SelectPlayer&Deselectcheckbox
SelectPickUp
ChangeTransform
Position:Y0.5,Rotation:X,Y,Z45,Scale:X,Y,Z0.5

RotatingPickUp
CreateNewScriptRotator
OpenMonDevelop &EditRotator
usingUnityEngine;
usingSystem.Collections;
publicclassRotator:MonoBehaviour {
voidUpdate(){
transform.Rotate(newVector3(15,30,45)*Time.deltaTime);
}
}

PlayTheGame:RotatingCube

36

10/10/2014

Creatingpickupobjects
MakingPrefabsAsset
CreateFolderPrefabsinProjectView
DragPickupobjectintoPrefabsfolder

CreateEmptyPickUps&Reset
DragPickupobjectintoPickUps
SelectYAxisinGizmo
ChangeLocal Globalmode

DuplicatePickUp(Ctrl+D)
Creating12Pickups

CollectingPickUpObject
CollectingPickUpObject
discussingphysics,collisionsandtriggers.
Collider:
SelectPlayer&selectcheckbox
CheckSphereCollider
OpenMonDevelop &EditPlayerController

voidOnTriggerEnter(Colliderother){
if(other.gameObject.tag =="PickUp"){
other.gameObject.SetActive(false);
}
}

37

10/10/2014

CollectingPickUpObject
Thereare3typesofcollidersinUnity3D:
Staticcolliders
Usedforcollisionsforanythingthatnevermovesinyourlevel
(levelfloors,walls,obstacles,etc)
theseshouldonlycontainacolliderwithout arigidbody.

Dynamiccolliders
Usedforcollisiondetectionfordynamicobjects(enemies,
bullets,boulders,etc)
thesetupisprettystraightforward,arigidbodyisattachedtoa
collider

Kinematiccolliders
Usedforcollisionsforanythingthatmovesusingcodeandnot
physics (movingplatforms,elevators,etc)
thesemusthave arigidbodymarkedaskinematicwithacollider.

CollectingPickUpObject
AddTag
AddTagPickUpUsingTagManager
SelectPrefabsPickUp
AssignTagPickUp
SelectcheckboxIsTriggerinBoxCollider

PlayIt!!!:CollectingBox

38

10/10/2014

CollectingPickUpObject
OneSmallMistake
StaticcollidersbychangingtheTransformpositionsincethiswill
impactheavilyontheperformanceofthephysicsengine

DynamicCollider:Addrigidbody intoPickUpPrefabs
TriggersdonotcollideGround

SimpleSolution:UncheckUseGravity
BetterSolution:Kinematiccolliders
CheckUseGravity&IsKinematic

Displayingtext
Displayingtext
Counting,displayingtextandendingthe
game.
CreateObject
CreateEmptyDisplayText&Reset
CreateGUITextCountText
MakingChild:DragintoDisplayText
ChangeTransform:X0,Y1
ChangeGUIText :PixelOffsetX10,Y10

39

10/10/2014

Displayingtext
SelectPlayerController:OpenMonDevelop &Edit
SelectPlayer&AssignCountText
public class PlayerController : MonoBehaviour {
public float speed;
public GUIText countText;
private int count;
void Start() {
count=0;
SetCountText ();
}
void FixedUpdate() { .. }
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag == "PickUp") {
other.gameObject.SetActive(false);
count = count + 1;
SetCountText ();
}
}
void SetCountText() {
countText.text = "Count: " + count.ToString();
}
}

Displayingtext
CreateGUITextWin
Text
MakingChild:Draginto
DisplayText
ChangeTransform:
X0.5,Y0.75
ChangeGUIText

public class PlayerController : MonoBehaviour {


public float speed;
public GUIText countText;
private int count;
public GUIText winText;
void Start() {
count=0;
SetCountText ();
winText.text="";
}
.

Anchor middlecenter
Alignment center

SelectPlayerController
OpenMonDevelop &Edit

void SetCountText() {
countText.text = "Count: " + count.ToString();
if(count==12) winText.text ="YOU WIN!";
}

SelectPlayer
AssignWinText

PlayIt

40

10/10/2014

Publishingthegame
Publishingthegame
Publishingthegametoawebplayer
SaveScene
File BuildSetting
SelectPlatformWebPlayer
Drag&DropMiniGame.unity
Build
CreateFolderBuilds
SaveasRollaBall_v01

Publishingthegame
WebPlay
CopyRollaBall_v01FoldertoWebServer
Failedtodownloaddatafile??
addingthecustomfilerequiredtodefineown
MIMETypes
putacustomweb.config inthesamefolderofthe
"*.unity3d"files

Play!!

<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".unity3d"mimeType="TYPE/SUBTYPE"/>
</staticContent>
</system.webServer>
</configuration>

web.config

41

10/10/2014

Publishingthegame

42

Das könnte Ihnen auch gefallen