Www.madwomb.com



Game Design: Introduction to Unity3D Notes by Jason Wiser

1. Unity3D Interface

2. Unity3D Concepts

3. Quick Intro Project:

o Terrain Creation, Textures, Trees

o 3rd-Person Controller

o Introduction to C# Scripting

o Sounds

[pic]

UNITY 3D INTERFACE:

MENU: offers easy access to all aspects of the program. In particular, note:

• File/Build Settings (to start any project)

• Edit/Project Settings/Input for helpful script-controlling inputs.

• Assets/Import Package to import useful prefabs

• GameObject and Component menus for easily building custom assets

SCENE View: View and transform all assets in the game from any desired angle. Orbit=[Alt]+LeftMouse, Pan=[Alt]+MiddleMouse, Zoom=[Alt]+RightMouse. Hit[f] to zoom and frame what is selected (“focus”). [Ctrl]+LeftClick to add or remove from selection.

GAME View: See through camera. Multiple cameras can split screen by percentages. Hit Play to view/ play game. Be careful: changes to assets during Play mode are reset when play is turned off (not saved).

CONSOLE Window: For checking errors thrown in scripts.

PROJECT Window: Where all assets are stored. Directly linked to the actual Project folder, will automatically update if anything is put into or taken out of the folder outside or inside Unity. Only change the contents of the Assets folder. Organize assets into subfolders: prefabs, scripts, etc.

HIERARCHY Window: Contents of the current scene. Organize by parenting similar objects under a named Empty Game Object, like putting all user interface GUIText objects under an Empty G.O. called “UI”.

INSPECTOR: Shows all Components and parameters for whichever G.O. is selected in the Hierarchy (instances) or Project (prefabs).

Context gears/dots: All Components have a gear or other context-sensitive button for changing parameters (like material Shaders) or adding assets, like texture PNGs.

Script Editor: Visual Basic (Unity 5.2 and above) or MonoDevelop (Unity 5.1 and earlier). Access by DoubleClicking a script. Write Unity scripts in either C# or Javascript, but never mix the two in the same script (ideally, avoid mixing in the same game). Scripts are Components added to G.O.s.

SCRIPTING NOTES:

• Add component/Script (C# default) or RightClick Project window to Create/C# Script

• Scripts easily access Components on their GO (RigidBody Mass, Drag, Gravity, etc).

• Unity won’t play game if script has error. See Console or footer for error messages.

• Select a term and hit [Ctrl/Cmd]+[‘] to access documentation.

• Mathf = super useful math functions collection, including clamp.

• Unity has a good physics engine built in, complete with collision systems raytracing, etc.

UNITY 3D : MAJOR CONCEPTS / TERMS:

• Game Object: The base of a thing in Unity. Just about everything in the game starts as an empty G.O., to which we add components to build it into an interactive asset.

• Component: everything we add to Game Objects to make them function as desired, including renderer, materials, particles, audio, physics, and custom scripts. Components can most easily be added to G.O.s and have their settings adjusted in the Inspector, with the G.O. selected.

• Scene: a game “level”. A game can have many Scenes, each sharing or with their own G.O.s, Controllers, and prefabs. File/New Scene to create a new Scene for an existing Project, File/New Project to start an entirely new game.

• Prefab: A container for a complete asset (collection of components, settings, and G.O.) used repeatedly in one or more Scenes. Can even be exported to use in other games. Create by dragging asset from Hierarchy to Project window. Each copy in game is an “instance”. Prefabs can be instantiated by code in a game (bullets, etc.).

• Physics: in Unity there are a number of components to manage physical interactions. Colliders (capsule, mesh, or box) manage object interactions and can be set for physics interactions (bouncing) or to trigger other effects (like activating a script if set to isTrigger). RigidBody enables the built-in physics engine, is applied to any object with actively interacting colliders (any object with a collider that is not the ground), and contains gravity which can be turned off for flying/space games.

• Controller: a component meant to manage a major part of the game. We write a custom GameController for a Scene and add an AnimationController to animated assets to manage the interaction of that asset’s animations with its scripts.

• 2D vs 3D: a 3D Unity game works with perspective and a 2D game uses flat parallax planes. Each must use their own physics prefabs, for example “RigidBody” for 3D and “2DrigidBody” for 2D. Set the initial gam system to 2D or 3D on project creation.

• AUDIO in Unity comes in 3 main forms:

o Audio Clips = Sound files (see Inspector for import settings/play preview. Flat game: Turn off 3D Sound)

o Audio Sources = G.O. with audio component to play SFX or music, added by dragging audio clip on G.O. Note “Play on Awake” and “Loop” settings to decide if audio starts immediately as G.O. is created and if it plays continuously. Also note volume settings.

o Audio Listener = What the audience hears. By default on the Main Camera, the single G.O. that receives audio. If 3D sound is on, distance of Sources from Listener changes audio volume.

• GUITEXT are empty G.O. with GUIText components applied. They are visible only in Game view, not Scene. Uses pixels in viewport space. Position by default is relative to: lowerLeft 0/0/0, upperLeft 1/0/0, upperRight 1/1/0, lowerRight 0/1/0.

• TAGS are identifiers which can be added to a G.O in the Inspector for scripts to exclude or include from an effect, or to find a specific tagged G.O., like the Player or GameController (both defaults)

UNITY 3D TUTORIAL: Quick Intro Project for Terrain, FPS, and Basic Scripting

SHORTCUTS:

• Doubleclick on an item in the hierarchy to center it.

• [alt]+ mouse buttons to navigate in the Scene window.

• [w]=move, [e]=rotate, [r]=scale

PART 1: SET-UP: Create a new Project. Go to Assets/ImportPackage and unpack: (1) Characters and (2) Environment (Terrain Assets, Tree Creator).

Add provided texture and sound files to the Assets folder to load in the Project.

PART 2: INTRODUCTION TO UNITY OBJECTS AND PHYSICS

1. In the Game Object menu, create a 3D > Cube. Note that it appears both in the Hierarchy and in the Scene view.

2. Navigate and transform: Hit [W] to move, [E] to rotate, and [R] to scale. Use [R] to Non-Uniform Scale the box into a wide and short platform.

To adjust the camera, hold [Alt] and click and drag the mouse buttons (left=orbit, right=zoom, middle=pan). Hit [F] to center the camera on the selected object.

3. Create another cube, and hit [W] to raise it above the platform cube. With this cube selected, go to the btotom of the Inspector panel (on the right), and click on [Add Component]. Under Physics add RigidBody (NOT physics2d). NOTE: each of thee rolldowns is a componet assigned to an emptyGO!

4. Hit Play to watch the box drop. Changes while in "play" mode are not saved, so we can go to Scene window and move the cube to see the default physics engine continue to effect it.

PART 3: HOW TO USE THE TERRAIN TOOLS FOR A QUICK 3D ENVIRONMENT

2. Create Terrain: Game Object > 3D Object > Terrain. Doubleclick the Terrain in the Hierarchy to center it in the Scene view. In Inspector > Terrain(Script), hit the rightmost button (gear) for Terrain properties. Set Terrain Width & height= 100 (down from 500) and leave height=600. Doubleclick in Hierarchy to center.

3. From Project, Add Standard Assets > Characters > FirstPersonCharacter > Prefabs > FPSController to the scene, lift the capsule above ground, and hit Play to move around (WASD = move, move mouse to look/turn, Space = jump).

4. Lights and Camera: GameObject/Lights/Directional Light for the Sun (intensity= 0.8, color=white-yellow, softshadows strength=0.3, rotate towards terrain) and Point Light for the bounce  (intensity= 0.3, color=white-blue, no shadows, position below terrain and off to a side, set range=200). Select Main Camera in the Hierarchy. Hit Delete.

5. Edit Terrain: Select the Terrain in the Hierarchy to view in Inspector:

• Hit 1st 3 buttons in the row of Terrain tools to change Terrain shape, sculpting upwards (or hold [shift] to push downward). Tool #2 allows you to hold [Shift] to choose a height and then release to draw at that height.

• Set brush size and opacity low and experiment.

• Use Tool #2 to type a higher base value (50.0) and hit "flatten" to allow downward molding (rivers). Also make clean paths (sample: hold [Shift]).

• Paint Brush: add textures (hit “Edit Textures/Add Texture”, drag PNG from the Project to the Albedo slot, set Size x = y = 5, hit [Add]). Strength=0.5:

o Texture #1: automatically applied everywhere

o Select Texture #2: paint in details

6. Add Trees: hit the trees button, and [edit trees]. Hit hot-button and add the default “Connifer” from TreeCreator > Trees Asset folder. Choose size range, [Ctrl]+click to erase.

PART 4: Introduction to scripting and audio: C# structures:

• DoubleClick script to open editor: MonoDevelop.

• For Manual (help): Select code and hit [Ctrl]+[‘].

• Comment selected lines: [Ctrl]+[alt]+[c].

• Deactivate Code Completion: Tools/General/Enable Code completion

[1]. Create a cube: GameObject > 3D Object > Cube.

a) In Inspector, hit Add Component to add Physics > RigidBody, turn on “Is Kinematic”.

b) Add a Component Physics/Box Collider, turn on “IsTrigger”.

[2]. Create a new C# Script: In Project Window: Right-click, choose Create > C# Script. Name it “Rotator,” hit Enter. Double-click the script in the Project to open in script editor. “void Start ()” and “void Update ()” are default methods.

• Delete Start, change class name to Rotator, add the following to Update and save:

public class Rotator : MonoBehaviour {

void Update () {

transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime); } }

[3]. Drag script onto cube in Hierarchy. [4]. Drag cube into Project to create Prefab.

[5]. Select cube in Hierarchy, hit [Ctrl]+[d] to duplicate for 3 cubes, and move in Scene.

Hit Play to test.

[6] To the FPSController G.O. add Component Physics > Capsule Collider (set to “isTrigger”). Move Capsule Collider Center forward on Z (try 2.0). Set Tag to “Player”.

Add an OnTriggerEnter method to the Rotator script (before the Class end-bracket):

public class Rotator : MonoBehaviour {

void Update () {

transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime); }

void OnTriggerEnter(Collider other) {

if (other.gameObject.tag == "Player"){

gameObject.SetActive(false); } } }

Add sounds to cube prefabs in Hierarchy, turn off “Play on Awake”.

Change OnTriggerEnter code:

void OnTriggerEnter(Collider other) {

if (other.gameObject.tag == "Player"){

//gameObject.SetActive(false);

GetComponent().Play(); } }

Hit Play and collide Player with each Cube to make all 3 sounds.

COROUTINES to add a delay between sound and destruction:

To do both make the sound and make the object disappear, the disappearance needs to be in a separate method and include a delay. This separate method needs to be a coroutine:

public class Rotator : MonoBehaviour {

void Update () {

transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime); }

void OnTriggerEnter(Collider other){

if (other.gameObject.tag == "Player") {

GetComponent().Play();

StartCoroutine(DestroyThis()); } }

IEnumerator DestroyThis(){

yield return new WaitForSeconds(0.5f);

Destroy(gameObject); } }

SCORING:

To provide scoring feedback, we need two new things: A graphic way to display the score (such as UI Text) and a Game Object containing a public script for managing the score.

[A] Start by creating an Empty G.O.: GameObject > CreateEmpty, name GameControlObj.

In Inspector apply the tag GameController.

Create a new C# script with the name GameController. Add this script to GameControlObj.

Doubleclick script to open in MonoDevelop. Be sure to add “using” namespace for UI to top:

using UnityEngine;

using System.Collections;

using UnityEngine.UI;

public class GameController : MonoBehaviour {

public GameObject textGameObject;

private int score;

void Start () {

score = 0;

UpdateScore (); }

public void AddScore (

int newScoreValue) {

score += newScoreValue; UpdateScore (); }

void UpdateScore () {

Text scoreTextB = textGameObject.GetComponent();

scoreTextB.text = "Score: " + score; } }

[B] Create a Canvas Text object: GameObject > UI > Text (note: will not be visible in Scene view, only Game view). In Inspector, change text field to say “Score and set Pos X and Pos Y toward a corner. Select your GameControlObj G.O. and drag the Text object into the empty public Text Game Object space in the GameController script component.

[C] Finally, add to the Rotator script:

1. Add a private variable and a new Start method:

private GameController gameController;

void Start () {

GameObject gameControllerObject = GameObject.FindWithTag ("GameController");

if (gameControllerObject != null) {

gameController = gameControllerObject.GetComponent (); }

if (gameController == null) {

Debug.Log ("Cannot find 'GameController' script"); } }

2. Add this line into the OnTriggerEnter method:

gameController.AddScore (1);

DOUBLING NOTE: If the audio plays twice, and the score registers two hits per cube, the reason is the FPS controller has a collider in its script in addition to the capsule collider we added, and both can hit the Cube Collider before the cube has a chance to delete itself. A simple solution is to turn off the cube collider after it registers the first impact.

3. Add this script to OnTriggerEnter above the audio play:

GetComponent ().enabled = false;

Adding Debug.Log

Not sure why certain behavior is occurring? Add a “return” to the debug log!

For example, in the scoring script above, to the updated Rotator script, in the OnTriggerEnter method, you can add…:

Debug.Log ("impact" + scoreValue);

…to see how many times the collider is activated. Hit Play and DoubleClick the lower-left corner of the play window to view the log.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download