SlideShare a Scribd company logo
This learning project will give you a sample of the essential tasks of a Unity programmer. These tasks can
also be useful in any other role when you want to customize the ways GameObjects behave. Although
many tasks in Unity don’t require programming, it can also be helpful to understand these fundamentals.
In these tutorials, you will create a simple script and add it to a GameObject as a component. You will be
introduced to the Integrated Development Environment (IDE) that comes with Unity, and explore the
default script that every Unity programmer starts from. You will change a GameObject using a script to
get a glimpse of the possibilities of scripting for your own projects.
Project Objective - By the end of this learning project you will be able to:
● Explain the role of the Integrated Development Environment (IDE) in Unity
● Open the IDE from the Unity Editor
● Create a new script component
● Understand the purpose of the default code generated within a newly created C# script
● Print a message to the Unity Editor console using a simple script
● Change a GameObject using a simple script
● Explain the relationship between scripts and components
Summary
In this tutorial, you’ll:
● Identify the role of code in creating experiences in
Unity.
● Discover what IDEs are, and what IDE is installed on
your system.
● Create a new script component.
1.Overview
In previous tutorials, you added components to GameObjects to change their properties and
behaviors. In addition to using the components provided in the Unity Editor, you can customize the
properties and behaviors of GameObjects by writing custom scripts in the C# language.
In this tutorial, you will create a simple “Hello World” component and add it to a GameObject. You
will see how you can use scripts to manipulate what appears in the Inspector window for any
GameObject. Along the way, you will learn about the tools and windows used for programming in
Unity.
Note: To view transcripts of videos, select Show transcript while playing each video. You can also
download a set of PDF files using the link in the Materials section at the top of each tutorial page.
2.Integrated development environments (IDEs)
What are IDEs?
Integrated Development
Environments (IDEs), such
as Visual Studio and Rider,
allow programmers to write
and debug code as
efficiently as possible. IDEs
support programming in a
wide range of languages
(e.g. C#, Java, Javascript,
Python, etc.); Unity
development is typically
done in C# (pronounced
“see sharp”) using Visual
Studio.
2.Integrated development environments (IDEs)
It is technically possible to write code in a simple text document, but IDEs provide
developers with a suite of tools to make programming easier. For example, most
IDEs include error detection to highlight when something is coded incorrectly, a
debugger to help locate the source of an error, syntax highlighting to make the
code easier to read, and code completion to instantly fill out lines of code.
Unity comes packaged with Visual Studio, and integrates with Visual Studio to
make coding and debugging much easier than it would be in a completely separate
IDE.
3.Check your IDE
Visual Studio is typically installed as a module during the
initial Unity installation. Follow these steps to set your IDE
to Visual Studio, and, if necessary, install the Visual
Studio Community module using the Unity Hub. Although
Unity can support other IDEs, this tutorial is based on
Visual Studio.
4.Create a new script
Let’s create your first script.
1. Open the 3D project you created for
Challenge: The Floor is Lava! You’ll
have an opportunity to customize this
project further with scripting.
2. Create a new empty GameObject in
the Scene by right-clicking in the
Hierarchy and selecting Create Empty.
3. Change the name of the new
GameObject to ScriptObject using the
Inspector window.
4. While your new GameObject is still
selected, select Add Component in the
Inspector window. Select the New Script
option.
5. The typical first lesson in
scripting in a new environment is
the “Hello, World!” exercise, which
is what we will do with this new
script. Name the new script
HelloWorld, and select the Create
and Add button.
6. The script is now added to the empty GameObject as a
component, and it also now appears in your project’s
Assets folder.
7. Double-click the new script to open it in
Visual Studio.
5.Next Steps
You are ready to start coding your new script component, which
is attached to an empty GameObject. Next, we will explain the
default script that you see when you open Visual Studio.
Summary
In this tutorial, you’ll:
● Identify the default script components of a new script
● Edit a script component in your IDE (Integrated
Development Environment).
● Display a message from a script in the Unity Editor’s
Console window.
1.Overview
Every time you create a new script, Unity gets you started with a
default script that contains the basic lines of code you will
need. In this tutorial, we’ll give you a tour of the default script,
write some code to use the functions provided, and link you to
some resources where you can learn more.
2.The default script
When you create a new script, you also create a new
public class that derives from the built-in class called
MonoBehaviour. When you named the component,
the same name was applied to this class and the
filename of your script. It is important that these
names match.
In the code, you will see a public class already set up.
It is called “HelloWorld”, the same as the name of the
script. These names should always be the same — if
you change the name of the script, you must also
change the name of this class.
The script also contains two functions, Start() and
Update().
The Start function runs once at the beginning of the game, and the
Update function runs at every frame of the game (more about frames
later).
3.Edit the Start function
1. Add the following code to the Start function, between the two {} brackets:
Debug.Log("Hello World");
2. Save the script using Ctrl+S (Windows) or
Cmd+S (Mac).
3. If the Console window is not showing in the
Unity Editor, open it with Ctrl+Shift+C
(Windows) or Cmd+Shift+C (Mac). The
Console window is where you can read
messages from scripts, including errors and
warnings, as the scripts run.
4. Play the game and look at the Console
window. The message “Hello World” appears
there.
4.Edit the Update function
1. Open the script again
and move the Debug.Log
line to the Update
function.
2. Save the script using
Ctrl+S (Windows) or
Cmd+S (Mac).
3. Select the Collapse
option on the Console
window, if it is not selected
already. This option will
simplify the display during
the next step.
4. Play the game and look at the Console window. This time, a counter appears next to the
“Hello World” message. This counter shows how many times the script has run and displayed the
message.
Since the script is now inside the Update function, it is running once for every
frame of the game. A frame is one single image in a series, like a frame of
motion picture film, that creates motion on the screen. When you press the
Play button and watch your game in the Game view, the Update function is
running many times continuously.
5.Add a property with a variable
To demonstrate the concept of scriptable components, you’ll add a variable to your
script and change its value in the Inspector window. A variable holds a value that
can vary. The value types you are most likely to encounter are int (integers), float
(floating point numbers, i.e., numbers that can have decimals), string (text), and
Boolean (true or false values). In the Transform Components you have used, the
float values for Scale X, Y, and Z are variables. In your script, you will replace the
“Hello, World!” message with a string variable that you can change in the Inspector
window through the HelloWorld Component. Through this variable, your
GameObject will have a property that you can manipulate from the Unity Editor.
1. Open the script in Visual Studio again.
2. Add a new variable as shown below:
5.Add a property with a
variable
1. Open the script in Visual Studio again.
2. Add a new variable as shown below:
public string myMessage;
3. Change the Debug.Log command as
follows:
Debug.Log(myMessage);
4. Save the script (Ctrl+S/Cmd+S).
5. In the Unity Editor, select the ScriptObject GameObject and look at the HelloWorld
Component in the Inspector. A new property appears where you can type a custom
message.
Enter the message of your choice.
6. Run the game and check the Console window. Your custom message now appears!
6.Next Steps
You can see that scripting in Unity can be very powerful: you
can make things happen during the user’s experience, and
you can make variables available in the Inspector window of
the Unity Editor so that you can adjust values later without
editing your script. Next, let’s use a script to make something
happen in the Scene.
Summary
In this tutorial, you will apply what you’ve learned about scripting to
a GameObject and make a visible change in the Scene.
In this tutorial you will:
● Edit the default code generated within a newly created C# script
● Use scripting to change the transform properties of a
GameObject
● Write code that utilizes the Unity APIs
1.Overview
This tutorial will introduce you to the Unity Scripting API, which defines the classes, along
with their methods and properties, that you can use in your scripts. (If you are unfamiliar
with these concepts, don’t worry — we will walk you through them.)
The Unity Scripting API is vast, but Unity provides plenty of comprehensive documentation, and
your IDE will guide you along the way. If you are interested in programming in Unity, you’ll learn
your way around the API as you try to solve new problems with scripting.
Here, you will use scripting to change the size of the ball in your “The floor is lava!” project. The
ball will get bigger as it rolls downhill. We’ll also show you how to change the position and
rotation in case you want to experiment more on your own.
2.Create your
script
1. Select the GameObject for your rolling ball.
2. In the same way you did in the previous tutorial,
add a new script to your GameObject. Name the new
script BallTransform, and double-click it in your
Assets folder (Project window) to open it in Visual
Studio.
Tip: You can close the windows on the right side of
your IDE window.
3.Increment the scale
To make the ball grow, we will add to its Scale property in every frame. You can experiment with how
much to make it grow in each frame by adjusting the component properties in the Inspector window.
To do this, we’ll initialize a public variable to hold the increments of the Scale property in the X, Y, and Z
dimensions. Then, we will add those increments to the Scale property of the ball in every frame.
1. Between the opening bracket of the class statement and the comment for the Start() method, add this
line to initialize a variable named scaleChange:
public Vector3 scaleChange;
This variable is public so that it will appear in the Inspector. The type of variable, Vector3, is
a data type for holding three values.
2. In the Update() method, start a new line and type:
transform.
3. This refers to the Transform Component of your GameObject. When you type the dot, you’ll see
a pop-up of all the properties and methods of the Transform Component.
4. Type or select localScale, then complete this line of code as follows:
transform.localScale += scaleChange;
Note: if localScale is not an option in the pop-up menu, be sure to check that Visual Studio is set to be
your IDE.
The operator += will add the values in scaleChange to the current scale values of the GameObject, so that
the ball grows.
5. Save your script
with Ctrl+S/Cmd+S.
The final result will
look like this:
4.Experiment with scale
1. Return to the Unity Editor and select the ball. In the Inspector, you will see the BallTransform component.
Notice how Unity automatically converts the variable name scaleChange in the script to Scale Change in the Inspector.
You can take advantage of this feature by always using camelCase for your public variables.
2. Given the current Scale properties of your ball, as shown in the Transform Component, consider how much to change
the scale in each frame. There are roughly 24 frames per second; therefore, if your ball has a Scale of 1,1,1, then Scale
Change values of 1, 1, 1 would multiply the ball’s size by 24 in each second! Experiment with some very small numbers
(such as 0.01), and select the Play button to test them.
3. Here are more things to try:
● When does the ball get too big for your course? Try adjusting the surfaces it rolls on to accommodate its larger size.
● Use different numbers for the three Scale Change values and watch your ball turn into an oblong spheroid that tumbles
instead of rolls.
● Are there other GameObjects you can make grow?
5.Try more transforms
Here are some lines of code you can use to change the rotation and position of GameObjects in the same way we
changed the scale. Try these on GameObjects in your own project to make your obstacle course more interesting.
Increment position
Increment rotation
Note: The script to increment rotation is a little different. The Rotate() method adds to the rotation of the
GameObject, whereas the other scripts change properties that are calculated in the script with the += operator.
Watch the video below for one example of ways to use these transform scripts in the challenge project.
6.Other resources for programming
You’ve only just begun discovering the power of scripting in Unity. If you are new to
coding and want to learn more, consider the Junior Programmer Pathway after
you have completed Unity Essentials. There, you will learn more of the
programming terms and concepts behind what you’ve experienced here.
Although programming is a helpful skill to have when developing projects with
complex interactivity in Unity, it is not necessary to be a coder to create with Unity.
For example:
● Certain types of projects, such as 3D visualizations and animations, don’t require code at all.
● Resources like Bolt for “visual scripting” allow developers to implement logic in their projects
using intuitive drag-and-drop graphical connectors without any knowledge of code or IDEs.
● The Unity Asset Store provides pre-made scripts and tools for the development of common
features, such as a first-person controller or an inventory system.
● Using Google, combined with sites like Unity Answers, Unity Forums, and Stack Overflow,
developers can copy, paste, and modify the coding solutions provided by other developers. (It
is surprising how far you can get with a little Googling and a lot of perseverance!)
7.Summary
This learning project has given you just a brief introduction to
scripting with Unity. You have enhanced your challenge project
with scripting: you learned about the default script and its Start()
and Update() methods, and you got a glimpse of the Unity
Scripting API by using code to change the Transform
Component of GameObjects. Scripting gives Unity endless
possibilities. Even if you aren’t a coder, you can now see the
breadth of what can be accomplished in Unity.

More Related Content

What's hot (20)

PPT
Introduction to Unity3D Game Engine
Mohsen Mirhoseini
 
PDF
Unity
Khaled Ismail
 
PPTX
Unity 3D, A game engine
Md. Irteza rahman Masud
 
PDF
Introduction to Game Development
Reggie Niccolo Santos
 
PPTX
Jetpack Compose.pptx
GDSCVJTI
 
PPTX
Unity 3D
gema123
 
PPTX
Game Design Principle
Naquiah Daud
 
PDF
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
David Salz
 
PPTX
Game development
reittes
 
PPTX
Game development life cycle
Sarah Alazab
 
PPTX
Develop Games With Cocos Creator - A Game Engine By Cocos
Luke Stapley
 
PPTX
Unity3D Programming
Michael Ivanov
 
PPTX
Unity Game Engine - Basics
FirosK2
 
PPTX
Game development
RareCoders
 
PPTX
Game Development with Unity
davidluzgouveia
 
PDF
Unity 2D game development
The NineHertz
 
PPTX
unity basics
Reham Maher El-Safarini
 
PPTX
Introduction to Unity3D and Building your First Game
Sarah Sexton
 
PDF
Making a Game Design Document
Equal Experts
 
PDF
Component-Based Entity Systems (Demo)
Nick Pruehs
 
Introduction to Unity3D Game Engine
Mohsen Mirhoseini
 
Unity 3D, A game engine
Md. Irteza rahman Masud
 
Introduction to Game Development
Reggie Niccolo Santos
 
Jetpack Compose.pptx
GDSCVJTI
 
Unity 3D
gema123
 
Game Design Principle
Naquiah Daud
 
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
David Salz
 
Game development
reittes
 
Game development life cycle
Sarah Alazab
 
Develop Games With Cocos Creator - A Game Engine By Cocos
Luke Stapley
 
Unity3D Programming
Michael Ivanov
 
Unity Game Engine - Basics
FirosK2
 
Game development
RareCoders
 
Game Development with Unity
davidluzgouveia
 
Unity 2D game development
The NineHertz
 
Introduction to Unity3D and Building your First Game
Sarah Sexton
 
Making a Game Design Document
Equal Experts
 
Component-Based Entity Systems (Demo)
Nick Pruehs
 

Similar to Unity - Essentials of Programming in Unity (20)

PDF
Unity 3d scripting tutorial
Blaž Gregorčič
 
PDF
2%20-%20Scripting%20Tutorial
tutorialsruby
 
PDF
2%20-%20Scripting%20Tutorial
tutorialsruby
 
PDF
Unity3d scripting tutorial
hungnttg
 
PDF
School For Games 2015 - Unity Engine Basics
Nick Pruehs
 
PDF
Let's make a game unity
Saija Ketola
 
PPTX
Overview of C# Script for Unity Game Development
Bryar Hassan
 
PDF
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
PPTX
Cmd unity withc
umairnoora
 
PDF
AI For Gaming lecture2 Unity and c# basics.pdf
YetundeLongeFolajimi
 
PDF
Introduction to Unity by Purdue university
asdf936939
 
PDF
How tomakea gameinunity3d
Dao Tung
 
PDF
Start Building a Game and Get the Basic Structure Running
mufti45
 
PPTX
WIG3004 virtual reality chapter3 software.pptx
GarethNg8
 
PDF
An Introduction to the Unity GamingEngine
Stevexm1
 
PDF
VR Workshop #2
Enrico Baracaglia
 
PDF
unity-clinic2-unityscript-basics
Darren Woodiwiss
 
PPTX
03 unity 3_d_part_2
Reham Maher El-Safarini
 
PDF
Creating First C# Script for game development and design
Bryar Hassan
 
PDF
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
noorcon
 
Unity 3d scripting tutorial
Blaž Gregorčič
 
2%20-%20Scripting%20Tutorial
tutorialsruby
 
2%20-%20Scripting%20Tutorial
tutorialsruby
 
Unity3d scripting tutorial
hungnttg
 
School For Games 2015 - Unity Engine Basics
Nick Pruehs
 
Let's make a game unity
Saija Ketola
 
Overview of C# Script for Unity Game Development
Bryar Hassan
 
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Cmd unity withc
umairnoora
 
AI For Gaming lecture2 Unity and c# basics.pdf
YetundeLongeFolajimi
 
Introduction to Unity by Purdue university
asdf936939
 
How tomakea gameinunity3d
Dao Tung
 
Start Building a Game and Get the Basic Structure Running
mufti45
 
WIG3004 virtual reality chapter3 software.pptx
GarethNg8
 
An Introduction to the Unity GamingEngine
Stevexm1
 
VR Workshop #2
Enrico Baracaglia
 
unity-clinic2-unityscript-basics
Darren Woodiwiss
 
03 unity 3_d_part_2
Reham Maher El-Safarini
 
Creating First C# Script for game development and design
Bryar Hassan
 
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
noorcon
 
Ad

Recently uploaded (20)

PDF
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
PDF
Next level data operations using Power Automate magic
Andries den Haan
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
Bridging CAD, IBM TRIRIGA & GIS with FME: The Portland Public Schools Case
Safe Software
 
Next level data operations using Power Automate magic
Andries den Haan
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Practical Applications of AI in Local Government
OnBoard
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
Kubernetes - Architecture & Components.pdf
geethak285
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
Proactive Server and System Monitoring with FME: Using HTTP and System Caller...
Safe Software
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
Ad

Unity - Essentials of Programming in Unity

  • 1. This learning project will give you a sample of the essential tasks of a Unity programmer. These tasks can also be useful in any other role when you want to customize the ways GameObjects behave. Although many tasks in Unity don’t require programming, it can also be helpful to understand these fundamentals. In these tutorials, you will create a simple script and add it to a GameObject as a component. You will be introduced to the Integrated Development Environment (IDE) that comes with Unity, and explore the default script that every Unity programmer starts from. You will change a GameObject using a script to get a glimpse of the possibilities of scripting for your own projects. Project Objective - By the end of this learning project you will be able to: ● Explain the role of the Integrated Development Environment (IDE) in Unity ● Open the IDE from the Unity Editor ● Create a new script component ● Understand the purpose of the default code generated within a newly created C# script ● Print a message to the Unity Editor console using a simple script ● Change a GameObject using a simple script ● Explain the relationship between scripts and components
  • 2. Summary In this tutorial, you’ll: ● Identify the role of code in creating experiences in Unity. ● Discover what IDEs are, and what IDE is installed on your system. ● Create a new script component.
  • 3. 1.Overview In previous tutorials, you added components to GameObjects to change their properties and behaviors. In addition to using the components provided in the Unity Editor, you can customize the properties and behaviors of GameObjects by writing custom scripts in the C# language. In this tutorial, you will create a simple “Hello World” component and add it to a GameObject. You will see how you can use scripts to manipulate what appears in the Inspector window for any GameObject. Along the way, you will learn about the tools and windows used for programming in Unity. Note: To view transcripts of videos, select Show transcript while playing each video. You can also download a set of PDF files using the link in the Materials section at the top of each tutorial page.
  • 4. 2.Integrated development environments (IDEs) What are IDEs? Integrated Development Environments (IDEs), such as Visual Studio and Rider, allow programmers to write and debug code as efficiently as possible. IDEs support programming in a wide range of languages (e.g. C#, Java, Javascript, Python, etc.); Unity development is typically done in C# (pronounced “see sharp”) using Visual Studio.
  • 5. 2.Integrated development environments (IDEs) It is technically possible to write code in a simple text document, but IDEs provide developers with a suite of tools to make programming easier. For example, most IDEs include error detection to highlight when something is coded incorrectly, a debugger to help locate the source of an error, syntax highlighting to make the code easier to read, and code completion to instantly fill out lines of code. Unity comes packaged with Visual Studio, and integrates with Visual Studio to make coding and debugging much easier than it would be in a completely separate IDE.
  • 6. 3.Check your IDE Visual Studio is typically installed as a module during the initial Unity installation. Follow these steps to set your IDE to Visual Studio, and, if necessary, install the Visual Studio Community module using the Unity Hub. Although Unity can support other IDEs, this tutorial is based on Visual Studio.
  • 7. 4.Create a new script Let’s create your first script. 1. Open the 3D project you created for Challenge: The Floor is Lava! You’ll have an opportunity to customize this project further with scripting. 2. Create a new empty GameObject in the Scene by right-clicking in the Hierarchy and selecting Create Empty. 3. Change the name of the new GameObject to ScriptObject using the Inspector window. 4. While your new GameObject is still selected, select Add Component in the Inspector window. Select the New Script option.
  • 8. 5. The typical first lesson in scripting in a new environment is the “Hello, World!” exercise, which is what we will do with this new script. Name the new script HelloWorld, and select the Create and Add button. 6. The script is now added to the empty GameObject as a component, and it also now appears in your project’s Assets folder. 7. Double-click the new script to open it in Visual Studio.
  • 9. 5.Next Steps You are ready to start coding your new script component, which is attached to an empty GameObject. Next, we will explain the default script that you see when you open Visual Studio.
  • 10. Summary In this tutorial, you’ll: ● Identify the default script components of a new script ● Edit a script component in your IDE (Integrated Development Environment). ● Display a message from a script in the Unity Editor’s Console window.
  • 11. 1.Overview Every time you create a new script, Unity gets you started with a default script that contains the basic lines of code you will need. In this tutorial, we’ll give you a tour of the default script, write some code to use the functions provided, and link you to some resources where you can learn more.
  • 12. 2.The default script When you create a new script, you also create a new public class that derives from the built-in class called MonoBehaviour. When you named the component, the same name was applied to this class and the filename of your script. It is important that these names match. In the code, you will see a public class already set up. It is called “HelloWorld”, the same as the name of the script. These names should always be the same — if you change the name of the script, you must also change the name of this class. The script also contains two functions, Start() and Update(). The Start function runs once at the beginning of the game, and the Update function runs at every frame of the game (more about frames later).
  • 13. 3.Edit the Start function 1. Add the following code to the Start function, between the two {} brackets: Debug.Log("Hello World");
  • 14. 2. Save the script using Ctrl+S (Windows) or Cmd+S (Mac). 3. If the Console window is not showing in the Unity Editor, open it with Ctrl+Shift+C (Windows) or Cmd+Shift+C (Mac). The Console window is where you can read messages from scripts, including errors and warnings, as the scripts run. 4. Play the game and look at the Console window. The message “Hello World” appears there.
  • 15. 4.Edit the Update function 1. Open the script again and move the Debug.Log line to the Update function. 2. Save the script using Ctrl+S (Windows) or Cmd+S (Mac). 3. Select the Collapse option on the Console window, if it is not selected already. This option will simplify the display during the next step.
  • 16. 4. Play the game and look at the Console window. This time, a counter appears next to the “Hello World” message. This counter shows how many times the script has run and displayed the message. Since the script is now inside the Update function, it is running once for every frame of the game. A frame is one single image in a series, like a frame of motion picture film, that creates motion on the screen. When you press the Play button and watch your game in the Game view, the Update function is running many times continuously.
  • 17. 5.Add a property with a variable To demonstrate the concept of scriptable components, you’ll add a variable to your script and change its value in the Inspector window. A variable holds a value that can vary. The value types you are most likely to encounter are int (integers), float (floating point numbers, i.e., numbers that can have decimals), string (text), and Boolean (true or false values). In the Transform Components you have used, the float values for Scale X, Y, and Z are variables. In your script, you will replace the “Hello, World!” message with a string variable that you can change in the Inspector window through the HelloWorld Component. Through this variable, your GameObject will have a property that you can manipulate from the Unity Editor. 1. Open the script in Visual Studio again. 2. Add a new variable as shown below:
  • 18. 5.Add a property with a variable 1. Open the script in Visual Studio again. 2. Add a new variable as shown below: public string myMessage; 3. Change the Debug.Log command as follows: Debug.Log(myMessage); 4. Save the script (Ctrl+S/Cmd+S).
  • 19. 5. In the Unity Editor, select the ScriptObject GameObject and look at the HelloWorld Component in the Inspector. A new property appears where you can type a custom message. Enter the message of your choice. 6. Run the game and check the Console window. Your custom message now appears!
  • 20. 6.Next Steps You can see that scripting in Unity can be very powerful: you can make things happen during the user’s experience, and you can make variables available in the Inspector window of the Unity Editor so that you can adjust values later without editing your script. Next, let’s use a script to make something happen in the Scene.
  • 21. Summary In this tutorial, you will apply what you’ve learned about scripting to a GameObject and make a visible change in the Scene. In this tutorial you will: ● Edit the default code generated within a newly created C# script ● Use scripting to change the transform properties of a GameObject ● Write code that utilizes the Unity APIs
  • 22. 1.Overview This tutorial will introduce you to the Unity Scripting API, which defines the classes, along with their methods and properties, that you can use in your scripts. (If you are unfamiliar with these concepts, don’t worry — we will walk you through them.) The Unity Scripting API is vast, but Unity provides plenty of comprehensive documentation, and your IDE will guide you along the way. If you are interested in programming in Unity, you’ll learn your way around the API as you try to solve new problems with scripting. Here, you will use scripting to change the size of the ball in your “The floor is lava!” project. The ball will get bigger as it rolls downhill. We’ll also show you how to change the position and rotation in case you want to experiment more on your own.
  • 23. 2.Create your script 1. Select the GameObject for your rolling ball. 2. In the same way you did in the previous tutorial, add a new script to your GameObject. Name the new script BallTransform, and double-click it in your Assets folder (Project window) to open it in Visual Studio. Tip: You can close the windows on the right side of your IDE window.
  • 24. 3.Increment the scale To make the ball grow, we will add to its Scale property in every frame. You can experiment with how much to make it grow in each frame by adjusting the component properties in the Inspector window. To do this, we’ll initialize a public variable to hold the increments of the Scale property in the X, Y, and Z dimensions. Then, we will add those increments to the Scale property of the ball in every frame. 1. Between the opening bracket of the class statement and the comment for the Start() method, add this line to initialize a variable named scaleChange: public Vector3 scaleChange;
  • 25. This variable is public so that it will appear in the Inspector. The type of variable, Vector3, is a data type for holding three values. 2. In the Update() method, start a new line and type: transform. 3. This refers to the Transform Component of your GameObject. When you type the dot, you’ll see a pop-up of all the properties and methods of the Transform Component. 4. Type or select localScale, then complete this line of code as follows: transform.localScale += scaleChange; Note: if localScale is not an option in the pop-up menu, be sure to check that Visual Studio is set to be your IDE. The operator += will add the values in scaleChange to the current scale values of the GameObject, so that the ball grows.
  • 26. 5. Save your script with Ctrl+S/Cmd+S. The final result will look like this:
  • 27. 4.Experiment with scale 1. Return to the Unity Editor and select the ball. In the Inspector, you will see the BallTransform component. Notice how Unity automatically converts the variable name scaleChange in the script to Scale Change in the Inspector. You can take advantage of this feature by always using camelCase for your public variables. 2. Given the current Scale properties of your ball, as shown in the Transform Component, consider how much to change the scale in each frame. There are roughly 24 frames per second; therefore, if your ball has a Scale of 1,1,1, then Scale Change values of 1, 1, 1 would multiply the ball’s size by 24 in each second! Experiment with some very small numbers (such as 0.01), and select the Play button to test them. 3. Here are more things to try: ● When does the ball get too big for your course? Try adjusting the surfaces it rolls on to accommodate its larger size. ● Use different numbers for the three Scale Change values and watch your ball turn into an oblong spheroid that tumbles instead of rolls. ● Are there other GameObjects you can make grow?
  • 28. 5.Try more transforms Here are some lines of code you can use to change the rotation and position of GameObjects in the same way we changed the scale. Try these on GameObjects in your own project to make your obstacle course more interesting. Increment position
  • 29. Increment rotation Note: The script to increment rotation is a little different. The Rotate() method adds to the rotation of the GameObject, whereas the other scripts change properties that are calculated in the script with the += operator. Watch the video below for one example of ways to use these transform scripts in the challenge project.
  • 30. 6.Other resources for programming You’ve only just begun discovering the power of scripting in Unity. If you are new to coding and want to learn more, consider the Junior Programmer Pathway after you have completed Unity Essentials. There, you will learn more of the programming terms and concepts behind what you’ve experienced here. Although programming is a helpful skill to have when developing projects with complex interactivity in Unity, it is not necessary to be a coder to create with Unity. For example: ● Certain types of projects, such as 3D visualizations and animations, don’t require code at all. ● Resources like Bolt for “visual scripting” allow developers to implement logic in their projects using intuitive drag-and-drop graphical connectors without any knowledge of code or IDEs. ● The Unity Asset Store provides pre-made scripts and tools for the development of common features, such as a first-person controller or an inventory system. ● Using Google, combined with sites like Unity Answers, Unity Forums, and Stack Overflow, developers can copy, paste, and modify the coding solutions provided by other developers. (It is surprising how far you can get with a little Googling and a lot of perseverance!)
  • 31. 7.Summary This learning project has given you just a brief introduction to scripting with Unity. You have enhanced your challenge project with scripting: you learned about the default script and its Start() and Update() methods, and you got a glimpse of the Unity Scripting API by using code to change the Transform Component of GameObjects. Scripting gives Unity endless possibilities. Even if you aren’t a coder, you can now see the breadth of what can be accomplished in Unity.