0% found this document useful (0 votes)
4 views36 pages

2.1 Introduction to C# Programming in Unity

The document provides an overview of variables, data types, and operators in C# for Unity, emphasizing the importance of scripting in game development. It outlines the setup of development environments, integration with IDEs like Visual Studio, and the basics of Unity scripting, including the lifecycle of scripts and debugging techniques. Additionally, it highlights best practices for C# scripting and the use of the Unity Console for logging and error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

2.1 Introduction to C# Programming in Unity

The document provides an overview of variables, data types, and operators in C# for Unity, emphasizing the importance of scripting in game development. It outlines the setup of development environments, integration with IDEs like Visual Studio, and the basics of Unity scripting, including the lifecycle of scripts and debugging techniques. Additionally, it highlights best practices for C# scripting and the use of the Unity Console for logging and error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Variables, Data Types, and Operators in

C# for Unity
Learning Objectives

• Understand the role of variables in C#.

• Learn about different data types and their usage.

• Gain proficiency in using operators for various operations.

2
• Setting Up Development Environment
• Introduction to Scripting
• C# Basics: Syntax and Structure
• Introduction to C#
• Basics of Unity Scripting in C#
Setting Up Development Environment
Unity supports the following IDEs:
• Visual Studio: When you install Unity on Windows and macOS, by default Unity also
installs Visual Studio or Visual Studio for Mac, respectively. By default, the External
Script Editor (menu: Unity > Preferences > External Tools > External Script Editor) is set
to Visual Studio
• Visual Studio Code: Unity supports opening scripts in Visual Studio Code (VS Code).
To open scripts in VS Code, go to Unity > Preferences > External Tools > External Script
Editor and select Visual Studio Code
• JetBrains Rider: Unity supports opening scripts in JetBrains Rider. To open scripts in
Rider, go to Unity > Preferences > External Tools > External Script Editor and select
Rider.

Image source: Unity.com


4
Setting Up Development Environment
Debug C# code in Unity
• You can use a debugger to inspect your source code while your application is running.
Unity supports the following code editors to debug C# code:
o Visual Studio (with the Visual Studio Tools for Unity plug-in)
o Visual Studio for Mac
o Jetbrains Rider
o Visual Studio Code (experimental)

Image source: Unity.com


5
Setting Up Development Environment
Visual Studio C# integration
• Unity integrates with Microsoft Visual Studio through the Code Editor Package for Visual
Studio. This package is pre-installed when you install Unity. If Visual Studio is installed
at the time you install Unity, then Unity uses Visual Studio to open and edit scripts by
default.

Image source: Unity.com


6
Setting Up Development Environment
Visual Studio C# integration

The Visual Studio Editor in the Package Manager Window


Image source: Unity.com
7
Setting Up Development Environment
Set Visual Studio as your default script editor
• Unity automatically uses Visual Studio as its default script editor if Visual Studio is
installed when you install Unity, or if you install Visual Studio as part of the Unity
installation process.
• To set your default script editor manually:
o Go to Edit > Preferences (macOS: Unity > Settings) in the main menu to open the
Preferences window.
o Open the External Tools menu.
o Click on the External Script Editor dropdown and select Microsoft Visual Studio. The
appearance of this option changes depending on the version of Microsoft Visual Studio you
have installed.

Image source: Unity.com


8
Setting Up Development Environment
Set Visual Studio as your default script editor

External Tool Settings


A: The External Script Editor dropdown menu, which displays the name and version of the selected
script editor.
B: The name and version of the Unity package that integrates with the selected script editor .
Image source: Unity.com
9
Setting Up Development Environment
Debug C# code in Unity
• After a code editor is installed, open Unity, go to Preferences > External Tools and set
the External Script Editor to your code editor.

Image source: Unity.com


10
Setting Up Development Environment
Debug C# code in Unity
• More detail, refer: https://docs.unity3d.com/Manual/ManagedCodeDebugging.html.

Image source: Unity.com


11
Setting Up Development Environment
Configure the code editor
• Visual Studio (Windows):
The Unity Editor installer includes an option to install Visual Studio with the Visual Studio
Tools for Unity plug-in.
If Visual Studio is already installed on your computer, open it and go to Tools > Get Tools and
Features… to locate and install the Visual Studio Tools for Unity plug-in.
• Visual Studio for Mac
The Unity Editor installer includes an option to install Visual Studio for Mac. If Visual Studio for
Mac is already installed on your computer, open it and go to Visual Studio > Extensions >
Install from file… to locate and install the Visual Studio Tools for Unity plug-in.
• JetBrains Rider
You can use the default installation of JetBrains Rider to debug code in Unity on Windows or
Mac
Image source: Unity.com
12
Setting Up Development Environment
Stack trace logging
Unity Console messages and log files can include detailed stack trace information. The
console also links to the line of code that generated the message. This is useful when you
want to identify the line, method, or sequence of function calls that caused the log entry to
appear.
More detail, refer: https://docs.unity3d.com/Manual/StackTrace.html

Image source: Unity.com


13
Introduction to Scripting
• Scripting is crucial in games, from basic ones to complex ones. It's needed for player
input responses, event sequencing, graphical effects, object behavior, and custom AI
systems
• Scripting is a skill that takes some time and effort to learn.
• GameObjects' behavior is dictated by attached Components in Unity. While Unity's
built-in Components are versatile, creating custom Components using scripts becomes
necessary for implementing unique gameplay features. These custom Components
enable triggering events, modifying properties, and responding to user input as needed.

Image source: Unity.com


14
Introduction to Scripting
• Unity supports the C# programming language natively. C# (pronounced C-sharp) is an
industry-standard language similar to Java or C++.
• In addition to this, many other .NET languages can be used with Unity if they can
compile a compatible DLL

Image source: Unity.com


15
Introduction to Scripting
Creating Scripts
• A new script can be created from the Create menu at the top left of the Project panel or
by selecting Assets > Create > C# Script from the main menu.
• The new script will be created in whichever folder selected in the Project panel. The
new script file’s name will be selected, prompting user to enter a new name.

Image source: Unity.com


16
Introduction to Scripting
Anatomy of a Script file
When double-click a script Asset in Unity, it will be opened in a text editor. By default, Unity
will use Visual Studio, but user can select any editor you like from the External Tools panel
in Unity’s preferences (go to Unity > Preferences).
The initial contents of the file will look something like this:

Image source: Unity.com


17
Introduction to Scripting
Anatomy of a Script file
• In Unity, a script connects with the engine by implementing a class derived from
MonoBehaviour, serving as a blueprint for a new Component attached to
GameObjects.
• The class name, derived from the file name, must match for attachment.
• Two key functions:
o Update: handling frame updates for GameObject actions. This might include
movement, triggering actions and responding to user input, basically anything that
needs to be handled over time during gameplay
o Start: called before gameplay, ideal for initialization tasks.

Image source: Unity.com


18
Introduction to Scripting
Controlling a GameObject
In Unity, a script serves as a blueprint for a Component, with its code activating only when
attached to a GameObject. Attachment can be done by dragging the script asset to a
GameObject in the hierarchy panel or the selected GameObject's inspector. The
Component menu's Scripts submenu displays all available scripts, including user-created
ones. The script instance looks much like any other Component in the Inspector:

Image source: Unity.com


19
Introduction to Scripting
Controlling a GameObject
Once attached, the script will start working when user press Play and run the game. It can
be checked by adding the following code in the Start function:

Debug.Log is a simple command that just prints a message to Unity’s console output. If
Play is pressed, the message should appear at the bottom of the main Unity editor window
and in the Console window (menu: Window > General > Console)

Image source: Unity.com


20
Introduction to C#
• C# (pronounced C sharp) is a versatile, modern, and object-oriented programming
language developed by Microsoft.
• Key Characteristics:
• Type-safe: Ensures data integrity and reduces errors.
• Efficient: Provides high performance and memory management.
• Object-oriented: Uses objects for modeling and structuring code.
• Applications of C#:
• Versatility: Widely used for diverse applications, including desktop, web, mobile, and game
development.
• Integration with Microsoft Technologies: Seamlessly integrates with the .NET framework and
Visual Studio.

Image source: Unity.com


21
Introduction to C#
• Why Choose C#?
• Career Opportunities: High demand in the industry, especially for developers working on
Microsoft platforms.

Image source: Unity.com


22
Introduction to C#
Absolutely, focusing on the fundamentals of C# is a solid approach when learning Unity
game development. Here are some key areas and concepts:
• Basic Syntax
• Functions and Methods
• Object-Oriented Programming (OOP)
• Unity-Specific Concepts
• Variables and Data Structures
• Unity Events and Delegates
• Coroutines
• Understanding GameObjects and Components
• Error Handling and Debugging
• Coding Best Practices
• Unity Documentation
• Practice with Simple Projects
Image source: Unity.com
23
Introduction to C#
C# programming plays a crucial role in Unity game development for several reasons:
• Unity Scripting Language
• First-Class Support
• Ease of Learning
• Powerful and Versatile
• Performance
• Unity API Integration
• Community and Resources
• Cross-Platform Development
• Integrated Development Environment (IDE)
• Extensibility

Image source: Unity.com


24
Basics of Unity Scripting in C#
• Unity scripts are written in C# or UnityScript (JavaScript) and control the behavior of
GameObjects in a Unity scene.
• All Unity scripts inherit from the MonoBehaviour class, which is the base class for scripts that
interact with Unity GameObjects.
• Key methods such as Start(), Update(), and OnTriggerEnter() are part of MonoBehaviour and
determine script behavior.

Image source: Unity.com


25
Basics of Unity Scripting in C#
• The script is a basic example that moves and
rotates a game object.
• It utilizes the Update method, which is called
every frame in Unity.
• The object is moved forward and rotated
based on the specified speed and time.

Simple Unity C# Script


Image source: Unity.com
26
Basics of Unity Scripting in C#
Script Execution Lifecycle:
• Unity follows a specific lifecycle for executing scripts:
• Awake(): Called when the script instance is being loaded.
• Start(): Called on the frame when the script is enabled, useful for initialization.
• Update(): Called once per frame for game logic updates.
• FixedUpdate(): Called at a fixed interval for physics-related updates.
• LateUpdate(): Called once per frame after all Update() functions.

Image source: Unity.com


27
Basics of Unity Scripting in C#
GameObjects and Components:
• Scripts are attached to GameObjects as components, allowing them to interact with the game
world.
• GameObjects can have multiple scripts, each handling different aspects of behavior.
• Components such as Transform, Rigidbody, and Collider can be accessed and modified via
scripts.

Image source: Unity.com


28
Basics of Unity Scripting in C#
Variables and Data Types:
• Scripts use variables to store and manipulate data.
• Common data types include int, float, string, bool, and more.
• Variables can be made public to be accessed and modified in the Unity Editor .
Unity Events and Messages:
• Unity provides built-in events and messages that scripts can respond to:
• OnMouseDown(): Called when the user clicks on a GameObject.
• OnCollisionEnter(): Called when a collision occurs.
• OnTriggerEnter(): Called when a GameObject enters a trigger collider.

Image source: Unity.com


29
Basics of Unity Scripting in C#
Asset Serialization:
• Unity's serialization system allows script data to be saved with scenes and assets.
• Serialized fields in scripts can be edited in the Unity Editor.
• Enables the creation of prefab instances with predefined behavior.
Debugging and Logging:
• Unity provides tools for debugging scripts, including the use of Debug.Log() for logging
messages to the console.
• Breakpoints and stepping through code are supported for more advanced debugging.

Image source: Unity.com


30
Basics of Unity Scripting in C#
C# Scripting Best Practices:
• Use meaningful variable and method names for clarity.
• Organize code into functions to improve readability.
• Optimize performance by using the appropriate Unity API methods.
• Regularly check the Unity Documentation for updates and new features.

Image source: Unity.com


31
The Console
• The Console is where we will be reading the Developer outputs. These outputs can be
used to quickly test bits of code without having to give added functionality for testing.
• There are three types of messages that appear in the default console. These messages
can be related to most of the compiler standards:
o Errors
o Warnings
o Messages

Image source: Unity.com


32
The Console
Errors
• Errors are issues or exceptions that will prevent the code from running at all.
Warnings
• Warnings are issues that will not stop your code from running, but may pose issues
during runtime.
Messages
• Messages are outputs that convey something to the user; they do not usually highlight
issues.

Image source: Unity.com


33
The Console
• We can even have the Console output our own messages, warnings and errors. To do
so, we will use the Debug class. The Debug class is a part of MonoBehaviour, which
gives us methods to write messages to the Console, quite similar to how you would
create normal output messages in your starter programs.
• The Console can be found in the labelled tab above the Assets region.

Image source: Unity.com


34
The Console
• The outputs of the console are more useful to the programmer, not the end user or
player.
• Example: write a simple message to the Console which will notify us when the Space
key was pressed. For this, we will use the Log method, which takes in an Object as a
parameter, which we will use a string in.

Image source: Unity.com


35
The Console
• Saving, compiling and running this code (by attaching it to a GameObject, of course), try
to hit the spacebar.

• Similarly, you can also output warnings by using the LogWarning method and errors with the
LogError method. These will prove to be useful for testing small bits of code without actually
having to implement them

Image source: Unity.com


36

You might also like