Beginning Unity Android Game Development: From Beginner To Pro 1st Edition Kishan Takoordyal
Beginning Unity Android Game Development: From Beginner To Pro 1st Edition Kishan Takoordyal
com
https://ebookmeta.com/product/beginning-unity-
android-game-development-from-beginner-to-pro-1st-
edition-kishan-takoordyal/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookmeta.com/product/beginning-3d-game-assets-
development-pipeline-learn-to-integrate-from-maya-to-unity-nova-
villanueva/
https://ebookmeta.com/product/beginning-matlab-and-simulink-from-
beginner-to-pro-2nd-edition-sulaymon-eshkabilov/
https://ebookmeta.com/product/beginning-hibernate-6-java-
persistence-from-beginner-to-pro-5th-edition-joseph-b-ottinger/
https://ebookmeta.com/product/nginx-from-beginner-to-pro-rahul-
soni/
Unity Development Cookbook: Real-Time Solutions from
Game Development to AI 2nd Edition Paris Buttfield-
Addison
https://ebookmeta.com/product/unity-development-cookbook-real-
time-solutions-from-game-development-to-ai-2nd-edition-paris-
buttfield-addison/
https://ebookmeta.com/product/introduction-to-game-design-
prototyping-and-development-from-concept-to-playable-game-with-
unity-and-c-3rd-edition-jeremy-gibson-bond/
https://ebookmeta.com/product/beginning-unity-editor-scripting-
create-and-publish-your-game-tools-1st-edition-benny-kok/
Beginning Unity
Android Game
Development
From Beginner to Pro
—
Kishan Takoordyal
www.allitebooks.com
Beginning Unity
Android Game
Development
From Beginner to Pro
Kishan Takoordyal
www.allitebooks.com
Beginning Unity Android Game Development: From Beginner to Pro
Kishan Takoordyal
Eau Coulee, Mauritius
www.allitebooks.com
To my family and the high school friends who have
supported me from the start
www.allitebooks.com
Table of Contents
About the Author���������������������������������������������������������������������������������xi
www.allitebooks.com
Table of Contents
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
Index�������������������������������������������������������������������������������������������������249
ix
About the Author
Kishan Takoordyal started at a young age
by learning programming with Python.
Since acquiring a greater interest in game
development, he has been developing games,
using the Unity game engine for more than
four years. He is also a Linux aficionado and
has worked on his own distribution. Currently,
he resides in his home country, Mauritius,
where he often participates in major technical
events and hackathons with Cyberstorm.mu,
while developing quality games and improving
his portfolio with new skills.
xi
About the Technical Reviewer
Simon Jackson is a longtime software
engineer and architect with many years of
Unity game development experience, as
well as the author of several Unity game
development books. He loves to create Unity
projects as well as lend a hand to help educate
others, whether via a blog, vlog, user group, or
major speaking event.
His primary focus at the moment is the
XRTK (Mixed Reality Toolkit) project. This is
aimed at building a cross-platform mixed reality framework to enable both
VR and AR developers to build efficient solutions in Unity and then build/
distribute them to as many platforms as possible.
xiii
Introduction
This book aims to help readers master the art of programming game apps
for Android, using the Unity3D game engine. It will help those wishing
to pursue a career, or hobbyists, understand basic concepts of game
development, using Unity. By the end of the book, readers will have gained
sufficient knowledge to confidently build an Android game.
The book starts by explaining simple programming concepts, to
familiarize beginners with the relevant jargon. Readers will then learn to
navigate the Unity interface and use basic tools (hand, move, rotate, scale,
rect). They will also learn to create basic 3D objects in the game, while
getting to know the purpose of several windows (Hierarchy, Inspector,
Scene, Game, Console, Project, Asset Store). The role of prefabs, Canvas
UI elements (such as Text, Button, Image, etc.), and several components
(transform, renderer, collider, rigidbody, etc.) will also be discussed.
In the last chapters, readers will learn to create a simple game for
Android, using the concepts studied in the previous chapters. Scripts will
have to be written to handle the behaviors of the player and enemies, as
well to handle other aspects of the game.
A lot of MonoBehavior structs (Vector3, Quaternion) and functions
(Awake, Start, Update, FixedUpdate, OnCollisionEnter, Coroutine)
also will be explained. Tips, such as switching to the universal rendering
pipeline, if targeting mobile platforms, will also be shared throughout the
book, to help improve in-game performance.
By the end of the book, the reader will have gained solid knowledge
for making basic Android games that can be upgraded later to make more
complex versions.
xv
CHAPTER 1
Programming
Concepts
Programming is all about taking a problem and defining a solution for it.
Every detail is elaborated to try and convey that solution to a computer.
For some, specific instructions are given to the computer system, to
perform tasks leading to the desired solution.
Thankfully, there are high-level programming languages to help us
write these solutions in a language closer to English than to 0s and 1s.
In exact terms, a programming language is a set of rules that provides a
means of instructing a computer what operations to perform.
Let’s consider an analogy. (Refer to Figure 1-1.) Suppose that we have
a couple of fruits and must make a salad out of them. The first step is to
analyze and define the problem. Specifically, input data (fruits) must be
identified and turned into expected output data (salad).
The second step is planning. One technique that programmers make
use of are flowcharts, which are a pictorial representation of a step-by-step
solution to a problem. They help us to focus on the program logic rather
than on the appropriate syntax of the programming language we’ll use.
The third step consists of actually coding the program. The logic in the
second step must now be converted into something that the computer can
understand. Various integrated development environments (IDEs) exist to
help programmers code in the programming language of their choice.
An IDE is just like a text editor but has several additional features to help
the development of a program, such as auto-completion or a debugger.
Auto-completion is a feature whereby sentences are automatically
completed with keywords that the IDE expects next, while a debugger
helps to run the program and possibly find bugs.
The fourth and final step is to test the program. A few errors might be
present, and to detect them, different types of test data must be input, and
the output must be consistent with the expected result. Debugging refers
to detecting, locating, and correcting bugs. These bugs might be syntax or
logical ones, among others, the former being, for example, a misspelled
instruction that the computer doesn’t understand, and the latter being
something like telling the computer to repeat an operation but not telling it
how to stop repeating.
2
Chapter 1 Programming Concepts
3
Chapter 1 Programming Concepts
Note You won’t be able to run the following code snippets yet,
but don’t worry. They are meant only to give you some basic theory
before we jump into Unity coding in subsequent chapters.
4
Chapter 1 Programming Concepts
1.1.5 Variables
Different operations can be performed on all sorts of data. In the long run,
it might be a good idea to make use of variables. A variable is a type of
special container to hold a specific kind of data. As an analogy, a variable
may be a wardrobe that serves to hold clothes and nothing else—not
kitchen utensils, for example. In C#, the classic way of declaring a variable
is as follows:
5
Chapter 1 Programming Concepts
1.1.6 Constants
Constants are just like variables, except that they can’t be modified after
declaration and will keep the value they were initialized with. The process
to declare a constant is similar to that to declare variables, except that the
const keyword must be placed before the data type field.
1.1.7 Comments
A comment is a programmer-readable annotation or explanation in a
script that usually makes it easier for users to understand what some
part of a code does. Comments are generally ignored by the compiler/
interpreter. In C#, comments can be written either in a single-line or
multiline way.
6
Chapter 1 Programming Concepts
1.2 Arrays
An array is a form of data storage structure similar to a variable, in the
sense that it is declared to hold a specific data type. Unlike variables,
however, arrays can hold multiple data values. When an array is created,
a predefined size is set for it. The array will thus hold the number of data
values equal to its size.
Data values found at indexes (positions) in the array may, just like
variables, be read, modified, or replaced by other data values of the same
type. The index of an array starts at 0 (the first data value), and the last
index will be equal to the size of the array minus one, because the first
index isn’t one.
7
Chapter 1 Programming Concepts
To get the length of an array, that is, how many values it can store, the
Length method can be called.
<arrayName>[<index>] = <value>;
<variable> = <arrayName>[<index>];
8
Chapter 1 Programming Concepts
int[] firstArray;
int size = 5;
1 + 1; // 2
9 -6; // 3
4 * 2; // 8
60 / 12; // 5
6 * 2 + 3; // 15
5 * (3 - 1) + 1; // 11
9
Chapter 1 Programming Concepts
int number = 1;
number + 1; // 2
number + 8 - 6; // 3
int number = 2;
number = number * 2; // 4
number * 4; // 16
1.3.3 Modulus
This is another useful arithmetic operator. It returns the remainder of an
integer division. Just as in the preceding operators, it can also be used with
variables and constants.
11 % 4; // 3
10
Chapter 1 Programming Concepts
Example Equivalent
int count = 5;
count++; // 6
count++; // 7
count--; // 6
11
Chapter 1 Programming Concepts
1.3.7 Casting
It may happen that when performing arithmetic operations, for instance,
an output of the undesired type is obtained. For example, if a programmer
has a variable declared as an integer in which they are about to store the
result of 5 * 1.61f, a float result will be obtained that can’t be stored in that
variable.
This is one of the situations in which casting comes in. Basically,
casting transforms a value of a particular data type into the same value,
but of a specified data type. Casting a float to an integer doesn’t round the
value. Only the integer part is returned.
int perfectInt;
float badFloat;
perfectInt = (int)badFloat; // 7
12
Chapter 1 Programming Concepts
Symbol Interpretation
== Is equal to
!= Is not equal to
> Is greater than
< Is less than
>= Is greater or equal to
<= Is less than or equal to
4 > 5 // false
180 < 450 // true
60 >= 70 // false
567 <= 550 // false
330 != 80 // true
45 > 45 // false
40 < 40.1f // true
90 >= 90 // true
1 == 2 // false
13
Chapter 1 Programming Concepts
!(1 == 2) // true
!((4 <= 8) && (6.1 >= 6)) // false
1.5 Selection
Normally, scripts are comprised of many lines of code. The sequence of
instructions is performed one after another. Sometimes, we wish to run
particular instructions based on specific conditions only. That’s where
selection comes in. By asking some sort of question, we can have the
computer system do something based on the answer. Control structures
14
Chapter 1 Programming Concepts
are what help us change this flow in programming. Every control structure
requires the indentation of code placed inside it. Indentation is really just
spaces or tabs.
if (condition) {
// Do something
}
string apple = "fruit";
int numberOfFruits = 0;
if (apple == "fruit") {
numberOfFruits++;
}
The else keyword can also be specified to make another block of code
run, if the condition in the if clause results in false instead.
if (condition) {
// Do something
} else {
// Do something else instead
}
15
Chapter 1 Programming Concepts
if (apple == "fruit") {
numberOfFruits++;
} else {
numberOfVegetables++;
}
if (condition) {
// Do something
} else if (another condition) {
// Do something
} else {
// Do something else instead
}
if (gender == "M") {
males++;
} else if (gender == "F") {
females++;
} else {
undefined++;
}
16
Chapter 1 Programming Concepts
if (condition) {
if (condition) {
// Do something
}
}
switch(variable) {
case value:
// Do something
break;
default:
// Do something else then
break;
}
switch (apple) {
case "fruit":
numberOfFruits++;
break;
case "vegetable":
numberOfVegetables++;
break;
default:
numberOfExceptions++;
break;
}
1.6 Iteration
Very often, some parts of a script may have to be repeated more than once.
Instead of duplicating the code x times, to keep the program easier to read,
modify, and debug, and, in some cases, make algorithms significantly
more efficient, loop control structures may be used. Code placed between
18
Chapter 1 Programming Concepts
the curly braces of loop control structure clauses will keep running, based
on a predefined condition. If, however, a condition always remains true,
the loop will run infinitely and cause the program to crash.
while (condition) {
// Do something
}
int number = 1;
19
Chapter 1 Programming Concepts
For example, a for loop can be used to perform the sum of all the even
numbers from 2 to 10. Basically, a variable, i, is declared as an integer,
initially given the value 2, and each time the loops run, its value will be
incremented by 2 and added to the variable sum, until i has a value greater
than 10.
int evenSum = 0;
20
Chapter 1 Programming Concepts
For reference, here’s the equivalent in a normal for loop. Note that
values.Length returns a value of 5, but the loop cannot be equal to this,
because the last index of the array will be 4.
21
Chapter 1 Programming Concepts
The break keyword instantly ends the execution of a loop and jumps
to the line of code just after and outside the loop. It can be used to end the
execution of a loop once a particular value has been found in an array, for
example, because it’s futile to continue checking the rest of the elements of
that array.
int alphabetRealPosition = 0;
1.7 Functions
You could have scripts with hundreds or thousands of lines of code. While
you can write everything in one continuous flow, wrapping code doing
one specific thing in one function makes the code appear more tidy, and
it’s easier to manage. In the preceding “Iteration” section (1.6), we learned
how to decrease code duplication by making loops. But what if some code
has to be run again multiple times but at different parts of the program?
That’s where functions come in.
22
Chapter 1 Programming Concepts
1.7.1 Basics
Functions contain code, and at desired parts in the script, they can be
“called” to perform the operation they were written to do.
void <functionName> () {
// Do something
}
Note that functions that do not return any value, that is, the script
doesn’t expect a value from them, have the type void. A void function
accomplishes its task and then returns control to the caller.
A simple function can be used to display something to the user. Of
course, the function won’t run by itself. That’s why in the main flow that
our code is running, we have to call it. The Debug.Log function will output
a logging message of the string we pass to it.
PrintHelloWorld();
void PrintHelloWorld() {
Debug.Log(“Hello World”);
}
1.7.2 Parameters
At times, we might also want to pass values to our functions, so that they
perform an operation with those, if, for example, we wish to reuse that
function for similar operations but with different values. The values that
we pass to functions are known as parameters, and they must be of the
same data type as the actual parameters.
23
Chapter 1 Programming Concepts
int a = 5;
int b = 4;
PrintSum(a, b, 2);
Taking the preceding example again, let’s assign the return value of the
function to c this time.
int a = 5;
24
Chapter 1 Programming Concepts
int b = 4;
int c = 0;
c = Add3Numbers(a, b, 2);
Let’s consider another example, this time with a boolean value. The
function will return false if the variable eat doesn’t contain the value
fruit.
if (itsAFruit(food)) {
numberFruits++;
}
25
Chapter 1 Programming Concepts
int a = 100;
void temporaryFunction(string b) {
int c;
}
1.8 Coroutines
Coroutines are very similar to functions, except that when you call a
function, it runs to completion before returning. Any action that takes
place in a function isn’t something that happens over time, as code in a
function is run within a single frame update. While it is possible to use
loops and checks to achieve this, it is often more useful to use a coroutine.
Unlike functions, which must be manually called each time to be executed,
coroutines can be set to run automatically at specified delays. Return
values from a coroutine are compulsory and may not be assigned to any
variable or used directly.
26
Chapter 1 Programming Concepts
StartCoroutine("<coroutineName>"); // or
StartCoroutine(<coroutineName>());
IEnumerator <coroutineName>(<parameters>) {
// Do something
yield return <returnValue>;
}
int numberFrames = 0;
StartCoroutine("CountFrames");
IEnumerator CountFrames() {
yield return null;
numberFrames++;
}
IEnumerator <coroutineName>(<parameters>) {
// Do something
yield return new WaitForSeconds(<numberOfSeconds>);
}
27
Chapter 1 Programming Concepts
28
Another random document with
no related content on Scribd:
Toisetkin nauroivat. Siihen loppui minun rohkeuteni; kiipesin
sänkyyn sisarieni viereen ja itkin.
"No onneksi olkoon, Antti! Kuluta terveydellä. Nyt sinä ensin voit
pitää häntä aputyttönä kuusi vuotta, kunnes hän on lukenut edes, ja
ansaita hyvät rahat hänestä, ja sitte saat siitä oikein kotona
kasvaneen palkkapiian. Niin, niin, Antti, sinä olet aina osannut oikein
pelata naisväen kanssa."
Jos otetaan vanha Martta pois luvusta, olen varma, ettei yksikään
näistä isistä ja äideistä vielä tähän asti ollut tuntenut sydämessään
mitään ahdistusta tämän surullisen toimituksen kestäessä. Mutta kun
naapurinvaimo nosti pikku Emman lattialle ja sanoi. "Nyt on sinun
vuorosi", syntyi yhtäkkiä merkillinen hiljaisuus tuvassa.
Pikku Emma! Kyllä oli leipä karkeaa ja vuode kova ja hame ohut
"esimiehen" luona, mutta sinä viihdyit siellä hyvin, kasvoit solakaksi
ja vahvaksi, kuin nuori, valkonen solkikoivu haassa, ja sinä tulit
iloiseksi kuin leivonen ja kauniiksi kuin aurinkoinen toukokuun päivä.
Seuraavan kerran kun sinut myytiin, kävi huonommin, sillä ostajan
hienon takin alla sykki huonompi sydän kuin "esimiehen" karkean
sarkatakin alla. Ja kun sinua ajattelen, en tahdo muistaa tuoreessa,
täyteläisessä kukoistuksessasi, joka tuli turmioksesi, enkä kalpeassa
kurjuudessasi kun tulit Nils veljen luo kuolemaan. En, tahdon
muistaa sinua kolmivuotiaana, suloisena palleroisena, joka
katseellasi voit pehmentää satoja sydämiä, juuri sellaisena kuin olit,
kun sinut myytiin kuudestakymmenestä kruunusta…
"Pystyyn, poika!"
Tämä varstalla puinti kello kahdesta yöllä aina hämäriin asti
iltapäivällä oli yleinen tapa talonpoikaisoloissa 1840-luvulla ja
jälkeenkin. Ne puimakoneet, mitä silloin löytyi, olivat liian kalliita
talonpojille ja liian suuriakin heidän pienissä tiloissaan. Puhdepuinti
oli niin muodoin välttämätön, jos mieli saada kaikki vilja puiduksi
ennen joulua, mikä oli kunnian-asia.
Siten kului kolme vuotta, kunnes olin "lukenut itseni edes", mikä
tapahtui jo samana keväänä kun täytin neljätoista vuotta. Seisoin
alinna käytävällä, ylläni liinatakki, jota Pohjosen emäntä parhaansa
mukaan oli koettanut värjätä mustaksi, yritys, joka menestyi vain
osittain; siitä tuli mustanruskea, mustempia ja vaaleampia täpliä
vierekkäin aivan kuin pantterin nahkassa. Heillä ei ollut varaa antaa
minulle parempaa; viimeiseksi vuodeksi oli Jaska huutanut minut
vain viidestätoista kruunusta. Arveltiin, että minä jo aloin ansaita
elatukseni, ja sen minä todella uskon itsekin.
Ja nyt minä oikein sain kuulla, kuinka suuren arvoinen nuori mies
minä olin talossa. En ihmettele, ett'ei Jaska tahtonut tehdä nuorta
mieltäni itserakkaaksi kaikella tuolla ylistyksellä.
Jollei Jaska nyt olisi myöntynyt, olisin minä, niin paljo kuin häntä
pelkäsinkin, syössyt sisään ja itse sekaantunut leikkiin. Mutta Jaska
hellitti purjeitaan ja sanoi:
Niin olin minä siis "myyty" toisen kerran elämässäni! Mutta olin
kuitenkin oikein iloinen. Herra Jumala, nythän minusta maksettiin.
Kauppa-Lassi ja minä.