Unity Introduction - Scott Goodwin's Website

gamgutturalMobile - Wireless

Dec 10, 2013 (3 years and 10 months ago)

77 views

I
NTRODUCTION

TO

U
NITY

3D

A useful guide for 03
-
60
-
377 and 03
-
60
-
477


Prepared for Dr. Scott Goodwin

Written by Andrew
Hlynka

So you want to make games



Computer games are made up of image files,
3d models, sound clips, etc. with computer
code that manages everything. The
player/user interacts with the game/program,
and the game/program reacts back.


Making a 3d model appear on the screen with
physics can be a time
-
consuming process if
you don

t know what you are doing. But
different gaming engines and editors exist
to help make game development a little
easier.

Unity 3D


A (mostly) free 3d game engine used for game
development, able to build games for PC, Mac,
Linux,
iOS
, Android, and console platforms. Code
can be done in C#,
Javascript
, or Boo.


A little different from what you are used to: you
have a window that directly shows you and lets
you edit game objects in your scene/level. It

s a
more visual way to create your project.


A popular tool used in many indie and commercial
games, such as
Dreamfall

Chapters, Shadow of the
Eternals, Max: The Curse of Brotherhood, Scrolls,
Slender: The Arrival and Bad
Piggies
.

A Game Engine


What Does It Do?


Game engines allow you access to variables, functions and other
built
-
in items to code your game more efficiently, as well as
run your game in an optimal way. Unity lets you code your game
with scripts, as well as giving you an editor to visualize the
game

s environment, and lets you debug the game in
realtime
.


Unity can be used for most of your game logic, game design, and
game compilation. Other multimedia assets (3d models,
animation, textures, audio, etc.) are recommended to be made in
other software tools (although Unity has been used to organize
such assets for app development and film making).


Other similar game engines also exist for use, such as
Unreal
Engine 3 SDK
, the
CryEngine

3 SDK
, and
Valve

s Source Engine
,
all free to try out. Other traditional methods can also be used
for coding, such as Microsoft Visual Studio, Eclipse, or a
simple text editor and compiler (note that simply displaying an
image on the screen can be difficult without additional tools
or libraries).

Links:

Main Website:

http://unity3d.com/


Download Program:

http://unity3d.com/unity/download/


Documentation and Tutorials:

http://docs.unity3d.com/Documentation/ScriptReference/


Installation:


Download Unity from this link:
http://unity3d.com/unity/download/


After installing, open the program. You may be
asked to either



A)
enter a serial number for the
full/professional/expensive version,



B)
to get a trial, or


C)
to keep the regular/free version.



The free version is all you will need for this
class.


Interface: Main Editor

Hierarchy
: List of all
game objects in your
scene.

Scene Window
: visual
of your current scene.

Game Window
: rendered
visual of what your game
will look and play like.

Play/Pause/Skip
: lets
you play/pause the game
for debugging purposes.

Inspector
: lists
properties of a
selected object.

Project Window
: lists folder hierarchy of
objects, scripts, textures, and other assets.

Console Window
: lets you print out and read debug
information as you write code and play the game.

Interface:
MonoDevelop

An additional software tool that comes free with Unity: meant to help you edit your
code and automatically update the game project in your Unity window. Is not necessary
to use to edit your code, as other code/text editors can also be used.

Text Editor
Window

Making a Simple 3d
Platformer


in Five Minutes:


Step 1: make a new project.


Step 2: make a simple level.


Step 3: make the character move from player input.


Step 4: test to make sure it actually works.


And you

re done!

Step 1: make a new project.


File
-
> New Project


Click “Create” Button (you can
import other items listed here,
but you won’t use them for this
example, they will just take up
space in your project folder).

Step 2: make a simple level.


What is the simplest
platformer

you
can make?


You must have two things: a player to
control, and some ground/platforms
for the character to jump on.


In our case, we will use Unity

s
simple built in game objects: a
capsule

for the player and a
plane

for the ground.


GameObject

-
> Create Other
-
> Plane



This will create the plane object with a
default size and location in the scene.

You can use your mouse and
the edit options to change the
position, size or rotation (or
edit these directly in the
inspector).

Repeat previous steps and create a “Capsule” game object,
as well as a light game object. Place the Capsule and light
above the plane, rotate and position the main camera to
have a better view of the objects.

Step 3: make the character move

from player input.


You need to write a script to make something
happen when the player enters input.


There are different ways to give a object
physics/movement. You can change the position of
the object directly (in which case all physics
calculations must be updated by you in code), or
you can give the object a

CharacterController


(for fake but easy to control movement) or

RigidBody


(for realistic but difficult to
control movement) to do most of the work.


This example will use

CharacterController


and
the
CharacterController.Move

function.

Select the capsule, in the Inspector click “
Add
Component
-
> Physics
-
> Character Controller


In the Project window, right click and “
Create
-
> C Sharp Script
”, name it

Move.cs
”. Open this and copy the following code in it. Save the file.

using
UnityEngine
;

using
System.Collections
;


public class Move :
MonoBehaviour

{




//variables to control how you move



public float speed = 6.0F;



public float
jumpSpeed

= 8.0F;



public float gravity = 20.0F;



private Vector3
moveDirection

= Vector3.zero;




//"void Update()" is called every frame of the game automatically.



void Update() {






//get component attached to the object with this script




CharacterController

controller =
GetComponent
<
CharacterController
>();






//if this object has ground underneath it...




if (
controller.isGrounded
) {




//find move direction based on input.




//(by default, "Horizontal" = left/right arrow keys, "Vertical" = up/down arrow keys, "Jump" = space bar)





moveDirection

= new Vector3(
Input.GetAxis
("Horizontal"), 0,
Input.GetAxis
("Vertical"));





moveDirection

=
transform.TransformDirection
(
moveDirection
);





moveDirection

*= speed;





if (
Input.GetButton
("Jump"))






moveDirection.y

=
jumpSpeed
;




}






//apply gravity to new move direction



//(always do this, even if already on ground: ground will stop you from going down)




moveDirection.y

-
= gravity *
Time.deltaTime
;






//move




controller.Move
(
moveDirection

*
Time.deltaTime
);



}

}

Drag the script onto the inspector
with the object selected to be
affected (the capsule).

Step 4: test to make sure it
actually works.



Simple: press that
Play

button at the
top of the Unity editor, and try it
out! You character should now move
and jump upon your input.


(if this doesn

t work, go back and
repeat Steps 1
-
3. Else, consult your
professor, your classmates, or your
Internet.)

And you

re done!


You just made the beginnings of a new game
using complex 3d physics, and it only took
you a few minutes!


Of course, you have to make art assets,
design better levels with goals, make
enemies/enemy
behaviours
, music, and other
stuff, but the hard part is done!


You can still go in much greater detail with
character control, camera movement, and
character AI.

Complex 3D Physics?


Don

t be too scared about physics and
collisions: Unity handles most of that for you!


Unity has different Physics components for your
game objects. You can find a list of them under

Component
-
> Physics.


Some items include
Rigid Body
,
Character Controller
, and many
types of
Colliders
.


Used together, physics components can make some
pretty cool stuff happen without you doing much
work. But if you want them to do something
exactly the way you want, you

ll have to
understand them in further detail on your own.

The capsule we made had a

capsule collider


attached to
it by default. It is a collider that is the same shape as
a basic capsule game object in Unity.


You can also give objects
sphere colliders
,
box
colliders
, and others. A
mesh collider
typically makes a
collider for a complicated shape. But colliders don

t
have to match the shape of the object: you can put a box
collider on this capsule if you wanted!


The plane also has a collider. By default, colliders
cannot move through each other in Unity. That

s why your
capsule doesn

t go through the ground!


You can also make special things happen in your code when
a collision occurs. Checking the box

Is Trigger


will
make hitting this object activate a function called

void
OnTriggerEnter
(Collider object)

.

You can define
this in your code to do anything you want! Look up other
default functions that automatically get called upon
collisions: they may occur upon staying or exiting a
collider as well!


Try changing the shape or size of your collider to see
what happens. What happens if you disable (uncheck the
box) the collider all together?

Did your code not work?


Sometimes your code won

t run, or it may do
something you weren

t expecting. When this
happens, you

ll need to
debug

your code
for errors.


There are different methods to get feedback
to what you are doing. Use what feels
natural to you in order to fix your
mistakes.

Debug Using the Console Window:


The Unity editor has a

Console


window, which will print
out any error messages that occur after saving new code,
or during playback. Check here first if your code isn

t
working properly.


You can also print out your own messages for debugging
purposes. This can let you know if certain parts of the
code are being called, or help you trace the values of
certain variables. Be careful, depending where you place
the line to print, it may get called many times, every
time the game is updated.

Debug Printing to the Console:


You must include the following at the top of
your class to access Unity

s console window:


using
UnityEngine
;

using
System.Collections
;



You can print using the function

Debug.Log
(string)

.There are other Debug
functions you can use as well, explore them to
see if they are any use to you. Place them in
appropriate spots of your code.


Debug.Log
(

This line of code was reached!

);


Debug using the Inspector:


Remember, when you select an
object, it

s properties can be seen
in the Inspector, even when playing
the game.


You can easily see values like the
object

s position, rotation, or
scale, and see them change in real
time.


If a script is attached, you can
also see all public variables in
that script in the Inspector. You
could make certain variables that
change public for this purpose
(although this is not considered
good coding practice).

Debug using the Debugger:


The built
-
in

Debugger


in Unity and
MonoDevelop

can give you more information about
when a function is called, or what value a
variable has at any given time.


In
MonoDevelop
, you can set

breakpoints


by
clicking next to each line you want to analyze.
This should make a red circle at these lines.


You must also click

Run
-
> Attach to Process


and choose the current Unity window that is
open. This will allow
Monodevelop

to directly
analyze the game as it runs the code.


When you run the game, it should now pause when
the code hits a break point.


You should be able to see information about the
call stack, your individual variables, etc.


(Unity may start a little slower, this should be normal)

(explore the
spots where
these arrows
point to
when
preparing to
use the
Debugger)

You should have an idea of how to use Unity now



But your character moves on your input, which
really isn

t the interesting part of this class


Making Character Move On
It

s Own:



Simple example where character will
rotate until it sees object in front of it,
then move forward to hit the object.



Step 1: add to previous example: make an
object/target to move to.


Step 2: modify
Move.cs

to look ahead and
move forward if it sees the target object,
else rotate.


Step 3: test to make sure it works.

Make a new game object (this time, make a “Cube”) and change it’s tag
to be something (it doesn’t matter what, but we will make it “Finish”
for now).

You can also add a new tag name by choosing “Add Tag…”. This may be
helpful for other, larger projects.

using
UnityEngine
;

using
System.Collections
;


public class Move :
MonoBehaviour

{




//variables to control how you move


public float speed = 6.0F;


public float
jumpSpeed

= 8.0F;


public float gravity = 20.0F;


private Vector3
moveDirection

= Vector3.zero;




//"void Update()" is called every frame of the game automatically.


void Update() {






//get component attached to the object with this script





CharacterController

controller =
GetComponent
<
CharacterController
>();






//if this object has ground underneath it...




if (
controller.isGrounded
) {




//find move direction based on input.




//(by default, "Horizontal" = left/right arrow keys, "Vertical" = up/down arrow keys, "Jump" = space bar)


//
moveDirection

= new Vector3(
Input.GetAxis
("Horizontal"), 0,
Input.GetAxis
("Vertical"));


//
moveDirection

=
transform.TransformDirection
(
moveDirection
);


//
moveDirection

*= speed;


//if (
Input.GetButton
("Jump"))


//
moveDirection.y

=
jumpSpeed
;








//forward direction relative to current object




Vector3 fwd =
transform.TransformDirection

(Vector3.forward);




//make a line going forward, record what it hits.




RaycastHit
[] hits;




hits =
Physics.RaycastAll
(
transform.position
, fwd, 100.0f);




moveDirection

= Vector3.zero;




foreach

(
RaycastHit

hit in hits)




{





//if we hit our target, we're facing the right direction





if (
hit.transform.tag

== "Finish")






moveDirection

= fwd;




}




//else, rotate until we face the right direction




if (
moveDirection

== Vector3.zero)





transform.Rotate

(0f,1f,0f);




}






//apply gravity to new move direction



//(always do this, even if already on ground: ground will stop you from going down)




moveDirection.y

-
= gravity *
Time.deltaTime
;






//move




controller.Move
(
moveDirection

*
Time.deltaTime
);



}

}

Modify your code to look like this.

(new content, be
sure to also
comment out
other parts as seen
here.)

Fun trick: which way is your character facing!?!?

Give him a nose by making a new game object, and
placing it
as his child in the hierarchy
to attach it to him.
Now you always now where he is facing!

When a object moves, all children underneath it automatically move with it. But child
objects can also move independently from the parent. You can make very simple
models with this without too much experience with 3d modeling or animation.

And now it should work!



but you can do much better AI then that, right?