0% found this document useful (0 votes)
1 views33 pages

GAME Programming Notes

The document provides an introduction to game programming using Unity and C#, covering the basics of the C# programming language, its features, and the Unity Editor environment. It outlines the steps for setting up Unity for C# development, including installation and configuration, as well as the key components of the Unity Editor. Additionally, it discusses the scripting capabilities within Unity, emphasizing the integration of Visual Studio for code editing and debugging.

Uploaded by

reshma.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views33 pages

GAME Programming Notes

The document provides an introduction to game programming using Unity and C#, covering the basics of the C# programming language, its features, and the Unity Editor environment. It outlines the steps for setting up Unity for C# development, including installation and configuration, as well as the key components of the Unity Editor. Additionally, it discusses the scripting capabilities within Unity, emphasizing the integration of Visual Studio for code editing and debugging.

Uploaded by

reshma.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

CS24305 – INTRODUCTION TO GAME PROGRAMMING

UNIT I Introduction to Unity and Game Development Basics

Overview of C# programming language - Introduction to the Unity Editor and C# scripting


environment - Setting up Unity for C# development - Unity Editor Overview (Scenes,
GameObjects, Inspector, Hierarchy)-Basic GameObjects manipulation (Position, Rotation,
Scale)- Components & Prefabs- Materials, Textures, and Basic Lighting- Simple Scripting
with C# (Variables, Functions, Events)- Building your first basic game.

Overview of C# programming language


Introduction to C#
C# (C-sharp) is a modern, object-oriented programming language developed by Microsoft as
part of the .NET framework. It was first released in 2000 and it has become one of the most
widely used languages for building Windows applications, web services, and more. C#
combines the power of C and C++ with the simplicity of languages like Java and Visual
Basic.
History of C#
C# was developed by Anders Hejlsberg at Microsoft as part of the .NET initiative. The
language was introduced as a part of the .NET Framework in 2000, aiming to provide a
simple and modern language that would overcome the limitations of other languages like C+
+ and Visual Basic. C# was designed to be a safe, efficient, and easy-to-use language for
building a wide range of applications.
C# has evolved with many updates and new features and including support for dynamic
programming, asynchronous programming, and LINQ (Language Integrated Query). It is
now a key language for building applications on Microsoft platforms such as Windows,
Azure, and .NET Core.
Key Features of C#
1. Object-Oriented Programming (OOP)
C# is an object-oriented programming language means it encourages the use of classes and
objects. The core concepts of OOP in C# are:
 Abstraction: Hiding the complex implementation details and exposing only the
essential features.
 Encapsulation: Bundling the data and the methods that operate on that data within a
class.
 Inheritance: Allowing one class to inherit the properties and methods of another class.
 Polymorphism: Enabling objects to take many forms and allows methods to behave
differently depending on the object calling them.
2. Simplicity
C# was designed to be simple and easy to use. Its syntax is clean, and many complex features
found in other languages, such as pointers, are either minimized or avoided altogether. Like
Java or C++, C# is similar but simpler.
3. Robustness
C# is a robust language that ensures high reliability and easy debugging. Features like
exception handling, garbage collection, and type safety contribute to its reliability allows
developers to write secure and error-free code.
4. Security
C# provides built-in security features like type safety, which prevents many types of errors
and security vulnerabilities. The Common Language Runtime (CLR) checks type safety and
makes sure that code does not access memory outside its boundaries.
5. Portability
C# is part of the .NET ecosystem, which allows us to write code that can be executed on
different platforms. With .NET Core (now .NET 5 and beyond), C# code can now be run on
platforms like Windows, macOS, and Linux, making it highly portable.
6. High Performance
C# code is compiled into intermediate language (IL) code, which is then executed by the
CLR. The use of Just-In-Time (JIT) compilation allows C# programs to run efficiently, and
optimizations in recent versions of the .NET framework have improved performance.
Execution of C# Code
The execution of a C# program involves three main steps:
1. Creating the Program
C# programs are written using text editors or Integrated Development Environments (IDEs)
like Visual Studio or Visual Studio Code. The source code is saved with a .cs extension.
2. Compiling the Program
The C# compiler (csc) converts the source code into an Intermediate Language (IL). This IL
is platform-independent and can be executed on any system that has the .NET runtime
installed.
Finding a Compiler:
 There are various online IDEs such as GeeksforGeeks ide, CodeChef ide etc. which
can be used to run C# programs without installing.
 Windows: Since the C# is developed within .Net framework initiative by Microsoft, it
provide various IDEs to run C# programs: Microsoft Visual Studio, Visual Studio
Express, Visual Web Developer
 Linux: Mono can be used to run C# programs on Linux.
 Programming in C#: Since the C# is a lot similar to other widely used languages
syntactically, it is easier to code and learn in C#. Programs can be written in C# in any
of the widely used text editors like Notepad++, gedit, etc. or on any of the compilers.
After writing the program save the file with the extension .cs.
3. Running the Program
The .NET runtime (CLR) executes the compiled IL code. The CLR translates the IL code into
native machine code, specific to the platform and architecture and it enables the program to
run on different operating systems and devices.
Example: A simple program to print Hello Geeks
// C# program to print Hello Students
using System;
namespace HelloStudents
{
class HelloStudents
{
// Main function
static void Main(string[] args)
{
// Printing Hello Students
Console.WriteLine("Hello Students");
Console.ReadKey();
}
}
}

Output
Hello Students
Explanation: Comments are used for explaining code and are used in similar manner as in
Java or C or C++. Compilers ignore the comment entries and does not execute them.
Comments can be of single line or multiple lines. Single line Comments:
Syntax:
// Single line comment

/* Multi line comments*/


 using System: It includes the System namespace for basic functions.
 namespace HelloStudents: This groups related classes.
 class HelloStudents: It defines the program, with a Main method.
 static void Main(): This is the entry point, static allows direct access, void means no
return.
 Console.WriteLine("Hello Students"); It prints text to the console.
 Console.ReadKey(): This pauses program (used in Visual Studio).
 Semicolons: C# is case-sensitive, end statements with ;.
Advantages of C#
 C# is very effective in managing the system. All garbage is collected automatically in
C#.
 There is no problem with memory leaks in C# due to the backup of high memory.
 The cost of maintenance is low and is safe to run compared to other languages.
 The C# code is collected for an intermediate language (generally (.NET) intermediate
language) which is a standard language, despite the target operating system and
architecture independently.
 Easy and easy to learn: C# is designed as an easy to learn, especially for a
programmer who is familiar with languages such as Java and C ++. It has a clear
syntax, which makes the code easy to read and write.
 Large standard library: C# has a large standard library that includes a wide range of
completed classrooms and features. This makes it easy for developers to do normal
features without writing much customized code.
 Strongly written: C# is a strongly written language, which means that data types are
checked on the collection. This helps to reduce errors and improve the reliability of
the code.
Applications
 C# is widely used to develop desktop applications, web applications and web services.
 It is used in large applications of Microsoft.
 C# is also used in the development of sports in unity.
 C# can be used to develop machine learning programs by using frames such as ml.net.
Ml.net. C# provides equipment for training and distribution to machine learning
models in applications.
 C# can be used to develop an IoT application using .Net IoT libraries. These
applications can be run on devices such as Raspberry Pie and Arduino.
 C# can be used to create a database application using ado.net or entity. These
applications can be connected to different database systems, such as Microsoft SQL
servers, Oracle and MySQL.
 C# can be used to develop mobile applications across platforms by using frames like
xamarin and .net maui. These applications can be run on Android, iOS and Windows
devices.
Introduction to the Unity Editor and C# scripting environment
Unity is a cross-platform game engine for creating games in both 2D and 3D. Unity supports
building games for many platforms such as iOS, Android, Windows, PlayStation, etc. The
Unity game engine was launched in 2005 and is one of the most famous game engines. Unity
gives the ability to the users to create games and experiences in both 2D and 3D. For the
main scripting in Unity, C# is used. Unity allows the specification of texture compression and
resolution settings for each platform that the game engine supports. Unity editor is supported
on Windows and macOS. An editor is available for Linux as well but it is in an experimental
stage.
How to install Unity?
 Visit the Unity's official download page.
 Agree the terms and conditions in the page.
 Click on Download Unity Hub.
Unity Hub is a complete installer for Unity game engine, Visual Studio (For C# Scripting)
and the game editor. Follow the instructions in Unity Hub and complete the installation along
with all the components. While installing, you will be asked to create a Unity account which
can be used to access all your projects as well as connect to the community. Once Unity is
installed, you will be able to access the game engine from the Desktop icon or from your
installed directory.
The Unity Community page helps you to discuss our problems and seek help from other
experienced users. In the site, you can do one of the five things:
 Visit the forums to see community discussions.
 Visit the answers section to see the questions and answers section.
 Visit Issue tracker to get the status of bugs that have been reproduced.
 Avail the Unity Live Help to have a live session on any topic related to Unity from a
verified community expert.
 Visit the documentation section
The Unity Editor is the primary interface used to create and develop projects within the Unity
game engine. It is a highly customizable environment composed of several key windows,
each serving a specific function in the development workflow.
Key Windows and their Functions:
 Scene Window:
This is the interactive 3D/2D viewport where users manipulate and arrange GameObjects
within the current scene. It allows for visual editing, positioning, and scaling of objects.
 Game Window:
This displays the view of the scene through the perspective of the active camera, simulating
what the player will see during gameplay.
 Hierarchy Window:
This lists all the GameObjects present in the current scene, providing a hierarchical overview
and allowing for selection and organization.
 Project Window:
This acts as a file explorer for the Unity project, displaying all assets, scripts, materials, and
other project files, typically rooted in the "Assets" folder.
 Inspector Window:
When a GameObject or asset is selected in the Hierarchy or Project windows, the Inspector
displays its properties and components, allowing for modification and customization.
 Console Window:
This window logs messages, warnings, and errors generated by scripts or the Unity Editor
itself, providing crucial feedback for debugging.
Editor Features and Tools:
 Tools:
The Editor includes various tools for manipulating GameObjects, such as the Hand tool for
panning, the Move tool for translation, the Rotate tool for rotation, and the Scale tool for
resizing.
 Playback Controls:
Play, Pause, and Step buttons allow for testing the game directly within the Editor, observing
its behavior and interactions.
 Customization:
The layout of the Unity Editor is highly customizable. Users can arrange and dock windows
as needed, save custom layouts, or utilize predefined layouts.
The Unity Editor provides a comprehensive and flexible environment for creating interactive
experiences, from game development to architectural visualization and beyond.
C# scripting environment
C# scripting environment allows developers to write and execute C# code as scripts, offering
a more lightweight and interactive way to utilize the language compared to traditional
compiled applications. This capability is particularly useful for tasks such as automation,
quick prototypes, or interactive experimentation.
Key components and features of a C# scripting environment:
 .NET SDK:
The fundamental requirement for C# development, including scripting, is the .NET
SDK. This package contains the C# compiler (csc.exe), the .NET Command Line Interface
(CLI), and the .NET Runtime necessary to execute C# applications and scripts.
 C# Interactive (CSI):
This is a Read-Eval-Print Loop (REPL) environment for C#. It allows for interactive
execution of C# code snippets and is ideal for testing small pieces of code or exploring
language features.
 Scripting Capabilities in .NET:
Recent advancements in .NET, particularly with .NET 10 (preview versions), have enhanced
the ability to run C# files directly as scripts using commands like dotnet run
[filename.cs]. The .NET CLI handles the compilation and execution behind the scenes.
 Integrated Development Environments (IDEs) and Code Editors:
While C# scripts can be run from the command line, using an IDE like Visual Studio or a
code editor like VS Code with extensions (e.g., C# DevKit) provides features like
IntelliSense, debugging tools, and project management capabilities, significantly improving
the development experience.
 Third-party Script Runners and Tools:
Tools like the C# Script runner in TeamCity or specialized libraries can enable executing C#
scripts in various contexts, including build automation or service tasks.
 Customizable Scripting Languages:
The flexibility of C# allows for the creation of custom scripting languages based on C#
principles, enabling tailored scripting solutions for specific needs.

Setting up Unity for C# development


Setting up Unity for C# development involves installing the necessary software and
configuring the Unity editor.
1. Install Unity and Visual Studio:
 Download Unity Hub: Obtain the Unity Hub installer from the official Unity
website.
 Install Unity Editor: Use the Unity Hub to install a desired version of the Unity
Editor. During this process, ensure you include the "Microsoft Visual Studio"
component in the installation options, as this integrates Visual Studio with Unity.
 Install Visual Studio (if not included with Unity): If you already have Visual Studio
or did not include it during the Unity installation, download and install Visual Studio
separately. When installing, select the "Game development with Unity" workload.
2. Configure Unity for C# Scripting:
 Open Unity Preferences: In the Unity Editor, navigate to Edit > Preferences (on
macOS, Unity > Settings).
 External Tools: Select the "External Tools" section within the Preferences window.
 Select Visual Studio as External Script Editor: From the "External Script Editor"
dropdown menu, choose the installed version of Microsoft Visual Studio. This ensures
that when you double-click a C# script in Unity, it opens in Visual Studio for editing.
3. Create and Edit C# Scripts:
 Create a new C# Script:
In the Unity Project panel, right-click and select Create > C# Script. Name the script
appropriately.
 Open and Edit:
Double-click the newly created C# script in the Project panel to open it in Visual Studio.
 Write C# Code:
Implement your game logic and functionalities using C# within Visual Studio.
 Save and Return to Unity:
Save your changes in Visual Studio and return to the Unity Editor. Unity will automatically
compile the script, and any errors will be displayed in the Console window.
4. Attach Scripts to GameObjects:
 Select a GameObject:
In the Hierarchy window, select the GameObject to which you want to attach the script.
 Add Component:
In the Inspector panel, click "Add Component" and search for the name of your C#
script. Select it to attach it to the GameObject.
This setup allows for seamless C# development within the Unity environment, leveraging
Visual Studio for code editing and debugging.
The Unity Editor overview
The Unity Editor is the primary interface for developing interactive 2D and 3D content, such
as video games, simulations, and virtual/augmented reality experiences, using the Unity game
engine. It provides a comprehensive set of tools and windows for creating, manipulating, and
managing project assets and game objects.
Key Windows and Their Functions:
 Scene View:
The interactive window where users build and manipulate the game world, positioning and
modifying game objects in 2D or 3D space.
 Game View:
Displays the output of the main camera, providing a real-time preview of what the player will
see during gameplay. This is used for playtesting.
 Hierarchy Window:
Lists all game objects within the currently open scene, allowing for organization and
selection of individual objects.
 Project Window:
Functions as a file explorer for the Unity project, displaying all assets (scripts, models,
textures, audio, etc.) and packages.
 Inspector Window:
Shows and allows modification of the properties and components of a selected game object or
asset.
 Console Window:
Displays messages, warnings, and errors generated by Unity or custom scripts during
development.
Basic Manipulation Of Gameobjects
In Unity, basic manipulation of GameObjects involves modifying their Position, Rotation,
and Scale, which are properties of the GameObject's Transform component.
1. Position (Movement):
 In the Scene View: Select the GameObject and use the Move Tool (hotkey: W). Drag
the colored arrows (gizmos) to move the object along the X (red), Y (green), or Z
(blue) axes. You can also drag the small squares at the center to move along two axes
simultaneously.
 In the Inspector: With the GameObject selected, locate its Transform component in
the Inspector window. Directly input values into the "Position" fields (X, Y, Z) to set
its exact coordinates in world space.
 Via Scripting: Access the transform.position property and assign a
new Vector3 value.
Code :
transform.position = new Vector3(1.0f, 2.0f, 3.0f); // Sets the object's position
transform.Translate(Vector3.forward * Time.deltaTime); // Moves the object relative to its
current position
2. Rotation:
 In the Scene View:
Select the GameObject and use the Rotate Tool (hotkey: E). Drag the colored circles (gizmos)
to rotate the object around the X (red), Y (green), or Z (blue) axes.
 In the Inspector:
In the Transform component, input values into the "Rotation" fields (X, Y, Z) to set the
object's rotation in Euler angles.
 Via Scripting:
 transform.rotation (Quaternion): For precise rotations, especially when dealing
with complex movements or avoiding gimbal lock.
Code:
transform.rotation = Quaternion.Euler(0, 90, 0); // Sets rotation to 90 degrees around Y-
axis
 transform.eulerAngles (Vector3): Easier to understand and manipulate for simple
rotations.
Code
transform.eulerAngles = new Vector3(0, 45, 0); // Sets rotation to 45 degrees around Y-axis
 transform.Rotate(): Rotates the object by a specified amount relative to its current
rotation.
Code:
transform.Rotate(0, 10 * Time.deltaTime, 0); // Rotates 10 degrees per second around Y-axis
 transform.LookAt(): Makes the object face a specific target.
Code:
transform.LookAt(targetObject.transform); // Makes the object look at the targetObject
3. Scale:
 In the Scene View: Select the GameObject and use the Scale Tool (hotkey: R). Drag
the central cube (gizmo) to scale the object uniformly on all axes. Drag the colored
squares to scale along a single axis.
 In the Inspector: In the Transform component, input values into the "Scale" fields
(X, Y, Z) to set the object's size.
 Via Scripting: Access the transform.localScale property and assign a
new Vector3 value.
Code:
transform.localScale = new Vector3(2.0f, 2.0f, 2.0f); // Doubles the object's size
Components and Prefabs
In Unity, Components and Prefabs are fundamental concepts for building and managing game
objects.
Components:
 Components are modular pieces of functionality that are attached to GameObjects.
 A GameObject itself is an empty container, and it gains behavior and properties by
having various Components added to it.
 Examples of common Components include:
o Transform: Determines the GameObject's position, rotation, and scale in the
scene. Every GameObject must have a Transform component.
o Mesh Renderer & Mesh Filter: Render 3D models.
o Collider: Enables physical interactions and collision detection.
o Rigidbody: Enables physics simulation for the GameObject.
o Scripts: Custom behaviors written in C# or other supported languages.
 Components are visible and configurable in the Inspector window when a
GameObject is selected.
Prefabs:
 Prefabs are reusable assets that act as templates for GameObjects.
 They encapsulate a GameObject along with all its attached Components, their
property values, and any child GameObjects.
 Prefabs are stored in the Project window and can be instantiated multiple times in
different scenes or within the same scene.
 The primary benefit of Prefabs is efficiency and consistency:
o Reusability: Create multiple identical instances of an object without having to
manually configure each one.
o Centralized Modification: Changes made to the original Prefab asset in the
Project window are automatically propagated to all instances of that Prefab in
the scenes (unless specific properties have been overridden on individual
instances).
o Version Control: Facilitates easier management of game assets and their
variations.
 A GameObject can be converted into a Prefab by dragging it from the Hierarchy
window into the Project window.
 Instances of Prefabs in the Hierarchy are typically indicated by blue text and a blue
cube icon, distinguishing them from regular GameObjects.
In Unity, materials, textures, and lighting work together to define the visual appearance
of objects within a scene.
Materials:
 Materials define how a surface should be rendered. They encapsulate properties such
as color tints, reflectivity, roughness, and references to textures.
 The appearance options available for a material are determined by the shader it
uses. Different shaders offer different parameters to control the material's interaction
with light.
Textures:
 Textures are 2D bitmap images that are applied to the surface of 3D objects. They
provide visual detail and can represent various surface characteristics beyond just
color, such as normal maps for bumps, metallic maps for shininess, or roughness
maps for surface irregularities.
 Textures are typically assigned to specific properties within a material's shader,
allowing the shader to use them during the rendering process.
Basic Lighting:
 Lighting illuminates the scene and allows objects to be visible. Unity offers various
light types, each with distinct characteristics:
o Directional Lights: Simulate distant light sources like the sun, casting parallel
rays across the entire scene.
o Point Lights: Emit light uniformly in all directions from a single point, similar
to a bare light bulb.
o Spot Lights: Project light within a cone shape, useful for localized illumination
like flashlights or car headlights.
o Area Lights: (Baked only) Emit light from a rectangular or disc-shaped area,
often used for soft, diffused lighting.
 Lights can be configured for different modes:
o Realtime: Lights are calculated dynamically in real-time, allowing for
changing properties and movement during gameplay.
o Baked: Light calculations are pre-computed and stored in lightmaps, offering
performance benefits but limiting dynamic changes.
o Mixed: Combines aspects of both realtime and baked lighting for a balance of
performance and flexibility.

 Simple scripting in C# involves utilizing fundamental programming


constructs such as variables, functions (methods), and events to
create executable logic.
 Variables:
 Variables are named storage locations used to hold data. In C#, they
must be declared with a specific data type before use.
 Code

// Declaring and initializing different types of variables


string userName = "Alice";
int age = 30;
bool isActive = true;
double price = 99.99;
Functions (Methods):
Functions, or methods in C#, are blocks of code designed to perform a specific task. They can
take input parameters and return a value, or perform actions without returning anything.
// A function that takes parameters and returns a value
public int AddNumbers(int num1, int num2)
{
return num1 + num2;
}

// A function that performs an action without returning a value


public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
Events:
Events provide a mechanism for objects to notify other objects when something significant
occurs. They are built upon delegates, which define the signature of the event handler
methods.
// 1. Define a delegate for the event handler
public delegate void MyEventHandler(object sender, EventArgs e);

// 2. Declare an event using the delegate


public class Publisher
{
public event MyEventHandler OnSomethingHappened;

// Method to raise the event


public void DoSomething()
{
Console.WriteLine("Publisher is doing something...");
// Raise the event if there are subscribers
OnSomethingHappened?.Invoke(this, EventArgs.Empty);
}
}

// 3. Create a subscriber class


public class Subscriber
{
public void HandleSomethingHappened(object sender, EventArgs e)
{
Console.WriteLine("Subscriber received the event!");
}
}

// Example usage:
// Publisher publisher = new Publisher();
// Subscriber subscriber = new Subscriber();
// publisher.OnSomethingHappened += subscriber.HandleSomethingHappened; // Subscribe
// publisher.DoSomething(); // This will trigger the event
UNIT II Object-Oriented Programming (OOP) Fundamentals

Understanding the principles of Object-Oriented Programming (OOP) - Classes, objects, and


inheritance in C# - Encapsulation, abstraction, and polymorphism - Implementing OOP
concepts in Unity scripts - Design patterns and best practices in Unity C# programming

Object Oriented Programming(OOP)


As the name suggests, Object-Oriented Programming or OOPs refers to languages that use
objects in programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the code can
access this data except that function.
OOPs Concepts:
 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state,
and behavior. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.

Object
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data
to the outside world, hiding the background details or implementation. Consider a real-life
example of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of the car or applying brakes will stop the car, but he does not know about
how on pressing the accelerator the speed is increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is
what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. In Encapsulation, the variables or data of
a class are hidden from any other class and can be accessed only through any member
function of their class in which they are declared. As in encapsulation, the data in a class is
hidden from other classes, so it is also known as data-hiding.

Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When
we write a class, we inherit properties from other classes. So when we create a class, we do
not need to write all the properties and functions again and again, as these can be inherited
from another class that possesses it. Inheritance allows the user to reuse the code whenever
possible and reduce its redundancy.

6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main
advantages of inheritance is that some derived class D has all the members of its base class B.
Once D is not hiding any of the public members of B, then an object of D can represent B in
any context where a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore
will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the
information to be sent.
Why do we need object-oriented programming
 To make the development and maintenance of projects more effortless.
 To provide the feature of data hiding that is good for security concerns.
 We can solve real-world problems if we are using object-oriented programming.
 It ensures code reusability.
 It lets us write generic code: which will work with a range of data, so we don't have to
write basic stuff over and over again.
In C#, classes, objects, and inheritance are fundamental concepts of Object-Oriented
Programming (OOP) that enable structured, reusable, and extensible code.
Classes:
A class is a blueprint or a template for creating objects. It defines the structure and behavior
that its objects will have, including data (fields) and actions (methods). Classes encapsulate
related data and functions into a single unit.
Code
// Example of a C# class
public class Car
{
// Fields (data)
public string Make;
public string Model;
public int Year;

// Method (behavior)
public void StartEngine()
{
Console.WriteLine("Engine started!");
}
}
Objects:
An object is an instance of a class. When a class is defined, no memory is allocated until an
object of that class is created. Objects represent real-world entities or concepts based on the
class blueprint.
Code
// Creating an object (instance) of the Car class
Car myCar = new Car();

// Accessing object members


myCar.Make = "Toyota";
myCar.Model = "Camry";
myCar.Year = 2023;
myCar.StartEngine(); // Calling a method
Inheritance:
Inheritance is an OOP mechanism that allows a new class (derived class or child class) to
inherit properties and methods from an existing class (base class or parent class). This
promotes code reusability and establishes an "is-a" relationship (e.g., a Dog "is a" Animal).
Code
// Base class
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}

// Derived class inheriting from Animal


public class Dog : Animal // The colon indicates inheritance
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}

// Usage of inheritance
Dog myDog = new Dog();
myDog.Eat(); // Inherited from Animal
myDog.Bark(); // Specific to Dog
In C#, a class can only inherit from a single base class, but it can implement multiple
interfaces. Inheritance is a powerful tool for building hierarchical relationships and
organizing code effectively.
Objects in OOPS
In Object-Oriented Programming (OOP), objects are instances of classes and represent real-
world entities or concepts. They encapsulate both data (properties) and behavior (methods)
into a single unit. Objects interact with each other, communicate through methods or
messages, and have a unique identity and state.
Let's take a real-life application of Objects in OOPS. In the real world, an animal can be
represented as an object in OOP. Let's say we have a class called "Animal" that defines the
common attributes and behavior of animals.
The Attributes of an Animal object are Type(e.g. Dog, Cat, Bird), Color, Age, Sound. The
Behavior (Capabilities) of an Animal Object can be Eat, Sleep, Make a Sound, or Move.
In this example, the "Animal" class acts as a blueprint, defining the common properties and
behavior of all animals. Each specific animal, such as a dog, cat, or bird, is an object
representing a unique instance of the "Animal" class with its specific attributes and behavior.
They promote code reusability and provide a modular and intuitive way to represent and
manipulate complex systems.
C# OOPS Concepts
OOPs concepts in C#
include classes and objects, encapsulation, inheritance, polymorphism and abstraction. C#
allows you to define classes as blueprints for creating objects, encapsulate data and methods
within classes, establish hierarchical relationships through inheritance, achieve flexibility
through polymorphism, simplify complex entities through abstraction, and provide method
overloading and overriding for code flexibility.C# OOPS concepts promote code reusability,
modularity, and maintainability in C# programming.
Encapsulation in C#
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP)
that promotes the concept of bundling related data and behaviors within a class. It
encapsulates the internal state (data) of an object and provides controlled access to that state
from outside the class.
Properties:
Properties provide a way to encapsulate private fields and expose them through controlled
access points. They allow us to define custom logic for reading and writing data, ensuring
data integrity, and enforcing business rules. In C#, properties are defined using the get and set
accessors.
The get accessor retrieves the value of the property, and the set accessor sets the value of the
property. We can also specify different access modifiers for the get and set accessors to
control read and write access separately.
Here's an example that demonstrates encapsulation in C# that shows the Oops concepts in
C#:
using System;
public class BankAccount
{
private string accountNumber;
private decimal balance;
public string AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
public decimal Balance
{
get { return balance; }
private set { balance = value; }
}
public void Deposit(decimal amount)
{
balance += amount;
}
public void Withdraw(decimal amount)
{
if (amount <= balance)
balance -= amount;
}
}
public class Program
{
public static void Main()
{
BankAccount myAccount = new BankAccount();
myAccount.AccountNumber = "123456789";
myAccount.Deposit(1000);
myAccount.Withdraw(500);
Console.WriteLine("Account Number: " + myAccount.AccountNumber);
Console.WriteLine("Balance: $" + myAccount.Balance);
}
}

Output:
Account Number: 123456789
Balance: $500
In this example, we have a BankAccount class that encapsulates the account number and
balance as private fields. The access modifiers private ensure that these fields can only be
accessed within the class.
Additionally, the BankAccount class provides public methods Deposit() and Withdraw() to
perform operations on the account balance. These methods encapsulate the behavior related
to depositing and withdrawing funds, allowing controlled access to modify the balance.
Inheritance in C#
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that enables
the creation of new classes (derived or child classes) based on existing classes (base or parent
classes). The derived class inherits the members (properties, methods, events) of the base
class and can add its members or modify the inherited ones. This allows for code reuse,
extensibility, and the creation of hierarchical relationships between classes.
Key Terminology:
 Base Class (Parent Class):
The class that is being inherited from. It serves as the foundation or blueprint for the
derived class. It defines common properties, methods, and behaviors shared by the
derived classes.
 Derived Class (Child Class):
The class that inherits from the base class. It extends the functionality of the base
class by adding new members or modifying the inherited members.
using System;
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
}
public class Program
{
public static void Main()
{
Shape shape1 = new Circle();
shape1.Draw(); // Output: "Drawing a circle."
Shape shape2 = new Rectangle();
shape2.Draw(); // Output: "Drawing a rectangle."
}
}

Output:
Drawing a circle.
Drawing a rectangle.
In this example, we have a base class Shape that defines a virtual method Draw(). The
derived classes Circle and Rectangle inherit from the Shape class and provide their
implementation of the Draw() method.
Here, we create objects shape1 and shape2 of the base class Shape but instantiate them with
the derived classes Circle and Rectangle, respectively. The overridden Draw() method in each
derived class is invoked based on the actual type of the object.
Abstraction in C#
Abstraction is a fundamental principle in Object-Oriented Programming (OOP) that enables
developers to create efficient, maintainable, and scalable code. It involves focusing on
essential features while hiding unnecessary details. In C#, abstraction is achieved through the
use of abstract classes, interfaces, and abstract methods.
At its core, abstraction allows us to create models that represent real-world entities or
systems. These models capture the essential characteristics and behaviors of the objects we
are working with while abstracting away the implementation details. By doing so, abstraction
provides a high-level perspective, allowing us to focus on the "what" instead of the "how". It
promotes code modularity, reusability, and flexibility.
using System;

// Abstract class representing a vehicle


public abstract class Vehicle
{
public abstract void Start(); // Abstract method for starting the vehicle
public abstract void Stop(); // Abstract method for stopping the vehicle
}
// Concrete class representing a car
public class Car : Vehicle
{
public override void Start()
{
Console.WriteLine("Car started.");
}

public override void Stop()


{
Console.WriteLine("Car stopped.");
}
}

// Concrete class representing a motorcycle


public class Motorcycle : Vehicle
{
public override void Start()
{
Console.WriteLine("Motorcycle started.");
}
public override void Stop()
{
Console.WriteLine("Motorcycle stopped.");
}
}

// Main program
public class Program
{
public static void Main()
{
Vehicle car = new Car();
car.Start();
car.Stop();

Vehicle motorcycle = new Motorcycle();


motorcycle.Start();
motorcycle.Stop();
}
}
Output:
Car started.
Car stopped.
Motorcycle started.
Motorcycle stopped.
In this example, we have an abstract class Vehicle representing a generic vehicle. It contains
two abstract methods: Start() and Stop(). These methods define common behaviors for
starting and stopping vehicles. We then have two concrete classes, Car and Motorcycle,
which inherit from the Vehicle class. They implement the abstract
methods Start() and Stop() according to their specific behavior.
In the Main method, we create instances of the Car and Motorcycle classes and call
the Start() and Stop() methods on these objects. The specific implementation of these
methods in each class is automatically invoked based on the object's type.
This example demonstrates how abstraction allows us to define a common interface (Vehicle)
for different types of vehicles, while each vehicle can provide its implementation for the
abstract methods. This abstraction helps in creating modular and extensible code by focusing
on the essential behaviors of each vehicle without exposing unnecessary implementation
details.
Polymorphism in C#
Polymorphism is a key concept in Object-Oriented Programming (OOP) that allows objects
of different classes to be treated as objects of a common base class or interface. It enables the
same code to be used with different types of objects, promoting flexibility, code reuse, and
extensibility.
Polymorphism is derived from the Greek words "poly" (meaning many) and "morph"
(meaning form). In the context of OOP, polymorphism allows objects of different classes to
be treated as objects of a common base class or interface. This means that we can use a single
code interface to represent multiple types of objects.
In C#, polymorphism can be categorized into two types: static polymorphism (compile-time
polymorphism) and dynamic polymorphism (runtime polymorphism). Let's explore each
type with examples:
1. Static Polymorphism (Compile-time Polymorphism)
Static polymorphism is achieved through method overloading and operator overloading. It
allows different methods or operators to be invoked based on the number, type, or order of
arguments at compile time.
Method Overloading Example:
using System;
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
// Main program
public class Program
{
public static void Main()
{
Calculator calculator = new Calculator();
int result1 = calculator.Add(2, 3);
int result2 = calculator.Add(2, 3, 4);
Console.WriteLine(result1); // Output: 5
Console.WriteLine(result2); // Output: 9
}
}

Output:
59
In this example, the Calculator class demonstrates method overloading. It provides two Add
methods with different parameter lists. The compiler determines which method to call based
on the number and types of arguments passed.
Here, we create an instance of the Calculator class and call the Add method with different sets
of arguments. The appropriate overloaded method is resolved at compile time, based on the
number of arguments provided.
Operator Overloading Example:
using System;

public class Vector


{
public int X { get; set; }
public int Y { get; set; }

public static Vector operator +(Vector v1, Vector v2)


{
return new Vector { X = v1.X + v2.X, Y = v1.Y + v2.Y };
}
}

// Main program
public class Program
{
public static void Main()
{
Vector v1 = new Vector { X = 1, Y = 2 };
Vector v2 = new Vector { X = 3, Y = 4 };
Vector result = v1 + v2;
Console.WriteLine($"Result: ({result.X}, {result.Y})"); // Output: Result: (4, 6)
}
}
Output:
Result: (4, 6)
In this example, the Vector class demonstrates operator overloading. It overloads
the + operator to enable vector addition. When the + operator is used between two Vector
objects, the overloaded method is invoked.
In this code, we create two Vector objects and add them using the + operator. The
overloaded + operator method is invoked, performing the vector addition.
2. Dynamic Polymorphism (Runtime Polymorphism):
Dynamic polymorphism is achieved through method overriding and interfaces. It allows
objects of different derived classes to be treated as objects of the base class or interface, and
the appropriate method is resolved at runtime based on the actual type of the object.
Method Overriding Example:
using System;
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}

public class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
// Main program
public class Program
{
public static void Main()
{
Shape shape = new Circle();
shape.Draw(); // Output: Drawing a circle.
}
}

Output:
Drawing a circle.
In this example, the Shape class defines a virtual Draw method, and the Circle class overrides
it with its implementation.
In this code, we create an object of the base class Shape but instantiate it with the derived
class Circle. When the Draw method is called, the overridden method in the Circle class is
invoked at runtime based on the actual type of the object.
The above clearly explains the Polymorphism, a C# oops concept.
Abstraction vs Encapsulation
Encapsulation and abstraction are two fundamental concepts in object-oriented
programming that promote modular and organized code design. While they share some
similarities, they serve different purposes and focus on different aspects of software
development. Here's a detailed comparison between encapsulation and abstraction:
 In encapsulation, data (attributes) and methods (behaviors) are bundled within a
class, controlling access to its internal state. In abstraction, complex systems are
simplified by focusing on essential features while hiding unnecessary details.
 Encapsulation aims to hide the internal implementation details of an object, providing
a controlled interface for interaction. Abstraction, on the other hand, aims to create a
conceptual model capturing essential characteristics of an object or system without
exposing its internal workings.
 Encapsulation achieves data hiding by making attributes private or protected to
prevent direct external access. Abstraction involves generalization, identifying
common features, and creating generalized concepts (e.g., classes, interfaces) to
represent those features.
 Access control is enabled through encapsulation by defining access modifiers
(e.g., public, private, protected) to control attribute and method accessibility. In
abstraction, information hiding is achieved by exposing only necessary information
through well-defined interfaces.
In summary, abstraction focuses on simplifying complex entities by hiding unnecessary
details through abstract classes and interfaces. Encapsulation, on the other hand, involves
bundling data and methods and controlling access to internal implementation details using
access modifiers and accessor methods. Both OOPS concepts C# contribute to code
modularity, maintainability, and reusability in C# OOPS concepts, but they serve different
purposes and operate at different levels of abstraction.
Implementing Object-Oriented Programming (OOP) concepts in Unity scripts
It enhances code organization, reusability, and maintainability. Unity's architecture is
inherently object-oriented, with GameObjects acting as containers for Components, which are
essentially classes.
Here's how to apply key OOP concepts in Unity:
1. Classes and Objects:
Classes: Define blueprints for GameObjects or custom data structures. Every Unity script is a
class that inherits from MonoBehaviour (for components) or ScriptableObject (for data
assets).
Code
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
void Update() { /* ... movement logic ... */ }
}
Objects: Instances of classes. GameObjects in a scene are objects, and you can create
instances of your custom classes within scripts.
2. Inheritance:
Create a hierarchy of classes where derived classes inherit properties and methods from a
base class.
Code
public class Enemy : MonoBehaviour
{
public int health = 100;
public virtual void TakeDamage(int amount) { health -= amount; }
}
public class SlimeEnemy : Enemy
{
public override void TakeDamage(int amount)
{
base.TakeDamage(amount); // Call base method
Debug.Log("Slime took damage!");
}
}
3. Polymorphism:
Allow objects of different classes to be treated as objects of a common base class. Use virtual
methods in the base class and override them in derived classes.
Code
// In a different script
public class CombatManager : MonoBehaviour
{
public void DealDamage(Enemy enemy, int damage)
{
enemy.TakeDamage(damage); // Calls the appropriate TakeDamage based on enemy
type
}
}
4. Encapsulation:
Bundle data (variables) and methods (functions) that operate on the data within a single unit
(class). Use access modifiers (public, private, protected) to control visibility.
Code
public class PlayerStats : MonoBehaviour
{
private int _currentHealth = 100; // Encapsulated private variable

public int CurrentHealth // Public property for controlled access


{
get { return _currentHealth; }
private set { _currentHealth = Mathf.Clamp(value, 0, 100); } // Controlled modification
}

public void Heal(int amount)


{
CurrentHealth += amount;
}
}
5. Abstraction:
Hide complex implementation details and expose only necessary functionalities through
abstract classes or interfaces.
Code
public abstract class Weapon : MonoBehaviour
{
public abstract void Attack(); // Abstract method, must be implemented by derived classes
}
public class Sword : Weapon
{
public override void Attack() { Debug.Log("Swinging sword!"); }
}

You might also like