With C# or “JavaScript” Telerik School Academy Unity 2D Game Development.

50
Unity Scripting With C# or “JavaScript” Telerik School Academy http://academy.telerik.com Unity 2D Game Development

Transcript of With C# or “JavaScript” Telerik School Academy Unity 2D Game Development.

Page 1: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Unity ScriptingWith C# or “JavaScript”

Telerik School Academyhttp://academy.telerik.com

Unity 2D Game Development

Page 2: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Table of Contents1. Creating and Using Scripts2. Variables Sent To Inspector3. Controlling Objects and

Components4. Input From Mouse, Touch,

Keyboard5. Game Loop and Events6. Time Management7. Creating and Destroying Game

Objects8. Coroutines9. Saving and Loading10.Good Practices

2

Page 3: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Creating and Using ScriptsAdd Script Components To

Objects

Page 4: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Creating and Using Scripts

Scripts are just normal components added to objects

They are not built-in, you "code" them and then compile them

They give you more control Can be written in C# (Mono) or

"JavaScript" (Unity style) Other .NET languages are

compatible (sort of)

4

Page 5: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Creating and Using Scripts

To add new script to an object select it and click "Add Component"

Start writing the name of the script – ex. "PlayerController"

Or simply write click on any directory on the "Project Browser", create it from there and drag it to an object

You should forget most OOP principles from now on – Unity is component-based and has its own standards

5

Page 6: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Default Script Parts Double-clicking a script will open it

in your IDE There are couple of things to

remember All components inherit from

MonoBehavior class All components are using the

UnityEngine namespace Do not declare anything in

namespaces (although Unity claims to support it)

Non-component classes (not attached to objects) do not need above requirements

6

Page 7: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Default Script Parts Start and Update functions are

included You may add FixedUpdate if using

Physics

7

using UnityEngine;

public class MainPlayer : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { }}

Page 8: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Default Script Parts Use Start method for initialization

Set needed variables Do not initialize with constructors Use the predefined methods -

GetComponent Use Update method for object

update on every frame – read input, change parameters

Use FixedUpdate method for Physics update to Rigidbodies – add forces, colliders

Use Debug.Log for debugging purposes

8

Page 9: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Platform Dependent Scripting

Sometimes you need to execute code on certain platforms:

More here: http://docs.unity3d.com/Manual/PlatformDependentCompilation.html 9

#if UNITY_EDITOR Debug.Log("Unity Editor");#elif UNITY_IPHONE Debug.Log("Unity iPhone");#elif UNITY_STANDALONE_WIN Debug.Log("Stand Alone Windows");#else Debug.Log("Any other platform");#endif

Page 10: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Variables Sent To Inspector What is supported by the

editor?

Page 11: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Variables and Inspector It is common to use some sort of

parameters to make the game work Movement speed Offsets Texts More

The easiest way is to set a public field

The editor will find it right away You will be able to change the

value run-time

11

private string myName;

Page 12: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Variables and Inspector Which fields can be serialized:

Public or with [SerializeField] attribute

Non-static, non-constant, non-readonly

Which types can be serialized: Primitive data types Custom non abstract classes and

structs with [Serializable] attribute Children of UnityEngine.Object Array or List<T> of serializable

types Avoid serializing complex objects

12

Page 13: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Controlling Objects and Components

The true power of Unity

Page 14: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Accessing Components From code you can change all

components' parameters to make the game change each frame

Additionally you can call methods, which are not available through the editor

Most common case Declare private variable for the

component in the class Get the component in the Start

method Change it in the Update method 14

Page 15: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Accessing Components Example:

15

using UnityEngine;

public class MainPlayer : MonoBehaviour { private RigidBody2D rigidbody;

void Start () { this.rigidbody = this.GetComponent<RigidBody2d>(); }

void Update () { this.rigidbody.mass = 10f; this.rigidbody.AddForce(Vector2.Up * 10f); }}

Page 16: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Accessing GameObjects You can access other GameObjects

Add public GameObject variable Drag'n'drop the object in the editor

to assign it

16

using UnityEngine;

public class MainPlayer : MonoBehaviour { public GameObject enemy;

void Start () { this.transform.position = this.enemy.transform.

position – Vector3.forward * 10f; }}

Page 17: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Accessing GameObjects You can access other GameObjects'

components Add public variable of the

component Drag'n'drop the object

17

using UnityEngine;

public class MainPlayer : MonoBehaviour { private Transform enemy;

void Start () { this.transform.position = this.enemy.

position – Vector3.forward * 10f; }}

Page 18: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Finding Game Objects You can find other objects by tag

or name

18

using UnityEngine;

public class MainPlayer : MonoBehaviour { private GameObject enemy; private GameObject[] enemies;

void Start () { this.enemy = GameObject.Find("Boss"); // name this.enemy = GameObject.FindWithTag("Boss"); // tag this.enemies = GameObject. FindGameObjectsWithTag("Enemy"); // collection }}

Page 20: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Device InputMouse, Keyboard,

Touchscreen

Page 21: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Input Input

All player input is accessed via the static Input class (do it in the Update)

You can read Buttons

Input Axes (Horizontal, Vertical)

Mouse movements

Accelerometer, Gyroscope

Multi-touch presses on touch screens

Edit -> Project Settings -> Input 21

Page 22: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Get Key You can use GetKey, GetKeyDown

and GetKeyUp All captured input is saved until

the next Update call This looks quite straightforward But avoid using it – you are device

dependent Not all devices have the same

buttons

22

if(Input.GetKeyDown(Keycode.Space)){ //Jump Code}

Page 23: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Get Button Buttons are way more generic They are not device dependent For example "Fire1" button is for

left-mouse click, tap on touchscreen and CTRL key on keyboards

Use GetButton, GetButtonDown and GetButtonUp

23

if(Input.GetKeyDown(Keycode.Space)){ //Jump Code}

Page 24: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Get Input Axes Input axes are mainly used for

movement Give you much smoother

experience "Horizontal" and "Vertical" Usually they return values

between -1 and 1 Depending on the direction Depending on the time the button

was pressed24

var hor = Input.GetAxis("Horizontal") * speed;this.transform.Translate(

new Vector3(hor, 0, 0) * Time.deltaTime);

Page 25: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Other Types of Input To get touchscreen information

Input.touches and Input.Touch structure

To get accelerometer information Input.acceleration

To get location information Input.location

To get mouse information Input.mousePosition

More here: http://docs.unity3d.com/ScriptReference/Input.html

25

Page 26: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Game Loop and Events

How The Game Is Running

Page 27: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Game Programming Game programming is usually

rendering frame after frame Before each frame different

calculations are done Object Positions and Rotations Colliding Physics

Unity fires different events before and after rendering the next frame

27

Page 28: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Regular Update Events Update

Called once per frame (not fixed time)

Executed before frames and animations

Perfect for inputs and getting different states of objects

FixedUpdate Called every fixed time seconds –

0.02 default Perfect for Physics Engine updates

and code LateUpdate

Called after all calculations Perfect for code that you want to

run after the frame is updated

28

Page 29: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Physics Events OnCollisionEnter2D,

OnCollisionStay2D, OnCollistionExit2D Called on every collision Enter – when collision starts Stay – when collision occurs Exit – when collision ends

OnTriggerEnter2D, OnTriggerStay2D, OnTriggerExit2D Fired only on trigger collisions

29

Page 30: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Other Events Start

Called before the first frame of Physics update on the object

Awake Called before the scene is loaded

and before the Start is called OnGUI

All GUI elements will respond to this event

OnMouseOver, OnMouseDown When a object has a mouse over or

clicked on 30

Page 31: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Game Loop Part 1

31

Page 32: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Game Loop Part 2

32

Page 33: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Time ManagementTime Is Money

Page 34: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Time Management Since the Update function is not

called on regular time intervals, you may get certain “lag” If the framerate drops Different CPU load

Consider the following code

34

public float distancePerFrame; void Update() { transform.Translate(distancePerFrame, 0, 0);}

Page 35: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Time Management If the framerate drop, you may see

different “laggy” results in the gameplay

The object will move with irregular speed

Solution is to scale all time dependent vectors (for example movement) with the delta time

You can get it from Time.deltaTime field

Now the object’s speed will be constant

35

public float distancePerFrame; void Update() { transform.Translate(distancePerFrame, 0, 0) * Time.deltaTime;}

Page 36: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Creating And Destroying

Game ObjectsUseful Techniques

Page 37: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Creating Game Objects It is very common to create

different objects run-time Usually you should use prefabs Instantiate method is used

Just drag’n’drop an object to the editor’s enemy field

37

public GameObject enemy;

void Start() { for (int i = 0; i < 5; i++) { Instantiate(enemy); }}

Page 38: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Destroying Game Objects

There is also an Destroy method You can set time after which the

object is destroyed

Destroy can also destroy only component

The following will destroy the script

38

void OnCollisionEnter2D(Collision2D otherObj) { if (otherObj.gameObject.tag == "Missile") { Destroy(gameObject, .5f); }}

Destroy(this);

Page 39: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

CoroutinesSometimes very useful!

Page 40: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Coroutine All functions are finished to the

end before the next frame is updated

Because of this animations cannot be done directly with code

This function will not gradually fade the object – it will disappear directly

40

void Fade() { for (float f = 1f; f >= 0; f -= 0.1f) { Color c = renderer.material.color; c.a = f; renderer.material.color = c; }}

Page 41: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Coroutine A coroutine will help you here Coroutine is executed over

sequence of frames instead of one Do declare coroutine The yielded value will pause until

the next frame of the game

41

IEnumerator Fade() { for (float f = 1f; f >= 0; f -= 0.1f) { Color c = renderer.material.color; c.a = f; renderer.material.color = c; yield return null; }}

Page 42: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Coroutine Then all you need is to start the

routine

You can also set time interval for the coroutine

You can use coroutines to reduce the checks in the Update method

42

void Update() { if (Input.GetKeyDown("f")) { StartCoroutine("Fade"); }}

yield return new WaitForSeconds(.1f);

Page 43: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Other Helpful Methods

Application!

Page 44: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Other Functions To invoke a method after certain

time

To load another scene

To quit the game

To pause the game set the Time.timeScale

And to resume set it to 1 44

Invoke("LoadLevel", 3f);

Time.timeScale = 0;

Application.LoadLevel("WinScene");

Application.Quit();

Page 45: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Saving And LoadingPersistence!

Page 46: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Saving And Loading The PlayerPrefs class have

methods to save and load values HasKey SetInt and GetInt SetFloat and GetFloat SetString and GetString

For saving and loading the whole game: http://goo.gl/3HZXZT

46

PlayerPrefs.SetInt("High Score", highscore);var highscore = PlayerPrefs.GetInt("High Score");

Page 47: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Good PracticesHigh Quality Code is important!

http://goo.gl/xPcrAx

Page 48: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Summary Coding gives you good control of the

game mechanics

Public fields are exported to the inspector

Use GetComponent to set different components

Use time management in your Update functions

How to use the Input class

Use coroutines where needed48

Page 49: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Unity Scripting

http://academy.telerik.com

Page 50: With C# or “JavaScript” Telerik School Academy  Unity 2D Game Development.

Free Trainings @ Telerik Academy

C# Programming @ Telerik Academy csharpfundamentals.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com