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

PDF
Game Design Fundamentals
PPTX
Unity 3D, A game engine
PPTX
Game Development with Unity
PDF
게임 개발자가 되고 싶어요
PPTX
Unity - Game Engine
PPTX
Unity 3d Basics
DOCX
SRS REPORT ON A ANDROID GAME
PPTX
Introduction to Unity3D and Building your First Game
Game Design Fundamentals
Unity 3D, A game engine
Game Development with Unity
게임 개발자가 되고 싶어요
Unity - Game Engine
Unity 3d Basics
SRS REPORT ON A ANDROID GAME
Introduction to Unity3D and Building your First Game

What's hot (20)

PDF
게임제작개론 : #7 팀 역할과 게임 리소스에 대한 이해
PPTX
Ux & ui
PDF
Unity introduction for programmers
PPT
Introduction to Unity3D Game Engine
PDF
쩌는게임기획서 이렇게 쓴다
PDF
Getting started with flutter
PPTX
Design phase of game development of unity 2d game
PDF
Unite2019 _ 학교에서 배우는 게임개발이란
PDF
Unity Introduction
PDF
Introduction to Game Development.pdf
PDF
게임 프로그래밍 기초 공부법
PDF
The Basics of Unity - The Game Engine
PDF
UX 101: A quick & dirty introduction to user experience strategy & design
PDF
NDC 2013 이은석 - 게임 디렉터가 뭐하는 건가요
PPTX
Software Engineer- A unity 3d Game
PPTX
Unity 3D game engine seminar
PPTX
Game development
PDF
Implementing imgui
PPTX
Android jetpack compose | Declarative UI
PPTX
UNITY 3D.pptx
게임제작개론 : #7 팀 역할과 게임 리소스에 대한 이해
Ux & ui
Unity introduction for programmers
Introduction to Unity3D Game Engine
쩌는게임기획서 이렇게 쓴다
Getting started with flutter
Design phase of game development of unity 2d game
Unite2019 _ 학교에서 배우는 게임개발이란
Unity Introduction
Introduction to Game Development.pdf
게임 프로그래밍 기초 공부법
The Basics of Unity - The Game Engine
UX 101: A quick & dirty introduction to user experience strategy & design
NDC 2013 이은석 - 게임 디렉터가 뭐하는 건가요
Software Engineer- A unity 3d Game
Unity 3D game engine seminar
Game development
Implementing imgui
Android jetpack compose | Declarative UI
UNITY 3D.pptx
Ad

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

PDF
Unity 3d scripting tutorial
PDF
2%20-%20Scripting%20Tutorial
PDF
2%20-%20Scripting%20Tutorial
PDF
Membangun Desktop App
PDF
Introduction to Box2D Physics Engine
PDF
Game UI Development_1
PDF
How tomakea gameinunity3d
DOCX
Getting started windows store unity
PPTX
Unity Game Engine - Basics
PDF
Java Is A Programming Dialect And Registering Stage Essay
DOCX
ID E's features
DOCX
Describe how you go from sitting in front of your system with the edit.docx
PDF
Getting started with appium
PDF
Introduction to Unity by Purdue university
PPT
Getting started with android studio
PDF
Gui builder
PDF
Start Building a Game and Get the Basic Structure Running
PPTX
Getting started with PlatformIO
PPT
Introduction to programming using Visual Basic 6
PDF
Diving into VS 2015 Day2
Unity 3d scripting tutorial
2%20-%20Scripting%20Tutorial
2%20-%20Scripting%20Tutorial
Membangun Desktop App
Introduction to Box2D Physics Engine
Game UI Development_1
How tomakea gameinunity3d
Getting started windows store unity
Unity Game Engine - Basics
Java Is A Programming Dialect And Registering Stage Essay
ID E's features
Describe how you go from sitting in front of your system with the edit.docx
Getting started with appium
Introduction to Unity by Purdue university
Getting started with android studio
Gui builder
Start Building a Game and Get the Basic Structure Running
Getting started with PlatformIO
Introduction to programming using Visual Basic 6
Diving into VS 2015 Day2
Ad

Recently uploaded (20)

PPTX
2018-HIPAA-Renewal-Training for executives
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Architecture types and enterprise applications.pdf
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
UiPath Agentic Automation session 1: RPA to Agents
PPTX
Configure Apache Mutual Authentication
PDF
Five Habits of High-Impact Board Members
PDF
Flame analysis and combustion estimation using large language and vision assi...
PDF
A review of recent deep learning applications in wood surface defect identifi...
PPTX
TEXTILE technology diploma scope and career opportunities
PDF
Zenith AI: Advanced Artificial Intelligence
PPT
Geologic Time for studying geology for geologist
PPTX
Chapter 5: Probability Theory and Statistics
PPT
Module 1.ppt Iot fundamentals and Architecture
2018-HIPAA-Renewal-Training for executives
Consumable AI The What, Why & How for Small Teams.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
Custom Battery Pack Design Considerations for Performance and Safety
sustainability-14-14877-v2.pddhzftheheeeee
Taming the Chaos: How to Turn Unstructured Data into Decisions
Architecture types and enterprise applications.pdf
Benefits of Physical activity for teenagers.pptx
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
UiPath Agentic Automation session 1: RPA to Agents
Configure Apache Mutual Authentication
Five Habits of High-Impact Board Members
Flame analysis and combustion estimation using large language and vision assi...
A review of recent deep learning applications in wood surface defect identifi...
TEXTILE technology diploma scope and career opportunities
Zenith AI: Advanced Artificial Intelligence
Geologic Time for studying geology for geologist
Chapter 5: Probability Theory and Statistics
Module 1.ppt Iot fundamentals and Architecture

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.