SlideShare a Scribd company logo
SCHOOL OF COMPUTING & DATA SCIENCE
AI For Gaming
Yetunde Folajimi, Ph.D.
SCHOOL OF COMPUTING & DATA SCIENCE
Lecture 2:
AI FOR GAMING 2
Yetunde Folajimi, PhD
Unity3D & C# Basics
SCHOOL OF COMPUTING & DATA SCIENCE
What is Unity3D?
• Unity3D is a powerful, cross-platform game engine and development environment.
• Widely used in the gaming industry for creating 2D and 3D games and
experiences.
• Supports a variety of platforms, including PC, console, mobile, and virtual reality.
AI FOR GAMING 3
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
What is Unity3D? (contd.)
• Features:
• Integrated development environment (IDE) with user-friendly interface.
• Visual scene editor for creating and editing game objects.
• Powerful scripting support using C#.
• Asset management and import system.
• The Unity Ecosystem:
• Unity Asset Store: A marketplace for game assets, tools, and plugins.
• https://assetstore.unity.com/
• Unity Services: Cloud-based solutions for building, testing, and
monetizing games.
• Unity Learn: A platform offering tutorials, courses, and learning resources.
• https://learn.unity.com/
• Unity Community: Forums, blogs, and events for Unity developers.
• https://unity.com/community
AI FOR GAMING 4
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Installing Unity3D with UnityHub
• Visit Unity's official website to download the Unity Hub: https://unity.com/
• Unity Hub: A central application for managing Unity installations and projects.
• Create or sign in to your Unity account.
• Select the appropriate version of Unity for your needs.
• Choose the platforms and modules you want to install.
• Creating a New Project:
• Open Unity Hub and click on the "New" button.
• Choose a project template (2D, 3D, or other templates).
• Name your project and choose a location to save it.
• Click "Create" to start your new Unity project.
AI FOR GAMING 5
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D Interface
• Key panels: Scene, Game, Hierarchy, Project, and Inspector.
• Customizable layout to fit your preferences.
AI FOR GAMING 6
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D Interface
• (A) The Toolbar provides access to your Unity Account and Unity Cloud
Services. It also contains controls for Play mode; Unity Search; a layer
visibility menu; and the Editor layout menu.
• (B) Hierarchy panel:
• Lists all game objects in the current scene.
• Organize game objects using parent-child relationships and groups.
• Select, add, or remove game objects from the scene.
AI FOR GAMING 7
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D Interface
• (C) Game View: Displays your game as it would appear when played
• Test and debug your game directly within the Unity editor
• Aspect ratio and resolution options for different devices.
• (D) Scene View: The region where you create and edit game objects
in your game.
• Navigation and manipulation tools for moving, rotating, and scaling objects.
• Grid and gizmos for easier placement and alignment.
AI FOR GAMING 8
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D Interface
• (E) Overlays contain the basic tools for manipulating the Scene view and the
GameObjects within it. You can also add custom Overlays to improve your
workflow.
• (F) Inspector Panel:
• Modify properties and settings of selected game objects.
• Add, remove, or edit components attached to game objects (e.g., scripts, colliders,
renderers).
AI FOR GAMING 9
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D Interface
• (G) Project panel:
• Displays all assets and folders in your Unity project.
• Import and manage game assets, such as textures, models, sounds, and
scripts.
• Create and organize folders to keep your project organized.
• (H) The status bar provides notifications about various Unity
processes, and quick access to related tools and settings.
AI FOR GAMING 10
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Working with the Unity Engine
• Inspector Panel:
• Modify properties and settings of selected game objects.
• Add, remove, or edit components attached to game
objects (e.g., scripts, colliders, renderers).
• Creating Game Objects
• Create game objects using the GameObject menu or
right-clicking in the Hierarchy panel.
• Basic game objects: Empty, 3D Object (Cube, Sphere,
etc.), 2D Object (Sprite), Light, Camera, and more.
• Game objects can be combined and customized to create
complex scenes.
• Importing Assets
• Import assets by dragging and dropping files into the
Project panel or using the Assets > Import menu.
• Supported file formats: FBX, OBJ (3D models), PNG,
JPG (textures), MP3, WAV (audio), and more.
• Unity Asset Store: Download and import assets directly
into your project.
AI FOR GAMING 11
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Working with the Unity Engine (contd.)
• Scripting in Unity:
• Unity supports C# scripting for game logic and
interactivity.
• Create a new script from the Assets menu or by right-
clicking in the Project panel.
• Scripts can be attached to game objects as components.
• Unity Scripting API
• Unity provides a rich scripting API for accessing and
manipulating game objects and components.
• Common namespaces:
• UnityEngine (core functionality)
• UnityEngine.AI (Implements Unity pathfinding features)
• UnityEngine.Analytics (collects core events and user properties)
• UnityEngine.SceneManagement (scene management functionalities).
• Documentation:
https://docs.unity3d.com/ScriptReference/
AI FOR GAMING 12
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Working with the Unity Engine (contd.)
• Building and Running Your Game
• Build and run your game using the File > Build Settings menu.
• Choose the target platform and adjust build settings as needed.
• Click "Build and Run" to create an executable and launch your
game.
• Testing and Debugging
• Test your game directly in the Unity editor using the Play button in
the Game View.
• Unity's Console panel displays error messages, warnings, and other
log output.
• Debug.Log() function can be used in scripts to output messages to
the Console.
AI FOR GAMING 13
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Working with the Unity Engine (contd.)
• Learning Resources:
• Unity manual: https://docs.unity3d.com/Manual/
• Unity Scripting Reference: https://docs.unity3d.com/ScriptReference/
• Unity Learn: https://learn.unity.com/
• Official Unity tutorials: https://unity3d.com/learn/tutorials
• Unity YouTube channel: https://www.youtube.com/user/Unity3D
• Unity Collaborate:
• A built-in version control system for working with teams.
• Enable Collaborate in the Unity Services window (Window > Unity Services).
• Invite team members, manage project versions, and resolve conflicts.
• Community and Support
• Unity forums: https://forum.unity.com/
• Unity Answers: https://answers.unity.com/
• Unity Asset Store support: https://unity3d.com/asset-store
• Tutorials and Sample Projects
• Roll-a-Ball, Space Shooter, Survival Shooter, 2D Roguelike, and more.
• Access these resources through the Unity Learn platform or download them from the Asset
Store.
AI FOR GAMING 14
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Introduction to C#
• C# is a powerful, versatile, and object-oriented programming
language.
• Developed by Microsoft as part of the .NET framework.
• Widely used in the software industry and a primary language for Unity3D
development.
• Easy to learn for beginners, with a syntax similar to Java and C++
• C# documentation: https://learn.microsoft.com/en-us/dotnet/csharp/
• C# Syntax Basics
• Statements end with a semicolon (;).
• Curly braces ({}) define blocks of code.
• Variables must be declared with a type before use.
• Comments: single line (//) and multi-line (/* ... */).
AI FOR GAMING 15
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# and Unity3D
• Accessing Unity Components:
• Unity provides various components (e.g., transform, rigidbody) that define
the properties and behavior of game objects. In C# scripts, you can access
and manipulate these components to modify the objects in your game.
• Event Handling:
• Events are actions or occurrences that happen during gameplay, such as a
button click or collision. You can handle events in C# scripts to trigger
specific actions or behaviors in response to these events.
• Script Execution Order:
• By default, scripts are executed in the order they are loaded, but you can
modify the execution order using script execution order attributes to ensure
correct dependencies and interactions.
AI FOR GAMING 16
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# and Unity3D (contd.)
• Attaching Scripts to Game Objects:
• Select the desired object in the Unity Scene view or Hierarchy window.
• In the Inspector window, click on the "Add Component" button and search for the script
name.
• Select the script to attach it to the game object.
• Communicating Between Scripts and Game Objects:
• Use public variables in the script that can be accessed and modified by other
scripts or the Unity Editor, or
• Use events or Unity's messaging system to send messages between scripts
and game objects.
• Script Best Practices:
• Organize your code
• Use meaningful variable and method names,
• Comment your code,
• Optimizing performance-intensive operations.
AI FOR GAMING 17
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity3D & C#: OOP Benefits
• Inheritance allows one class to inherit the fields and methods of another
class, which can be useful for creating more specialized game objects.
• Example: A base class Enemy that has general methods like TakeDamage()
could have a Zombie class that inherits from Enemy and overrides the
TakeDamage() method to include zombie-specific behavior.
• Polymorphism allows developers to use methods from a base class, but
define different implementations for those methods in derived classes.
• Example: For a method in the game manager that accepts an Enemy object and
calls TakeDamage(). You could pass in a Zombie object and, thanks to
polymorphism, the Zombie version of TakeDamage() would be called.
• Encapsulation protects the internal state and functionality of game
objects.
• In a Player class with a private health field. Use a public method like
TakeDamage(int damage) to control how health is reduced, rather than allowing
other classes to change health directly.
AI FOR GAMING 18
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# and Unity3D: OOP Benefits (Contd.)
• Event-driven programming model allows game objects to respond to a
variety of input or events, such as mouse clicks or button presses.
Delegates can be used to create and control events, which are often
used for creating game logic.
• Example: Define a delegate public delegate void OnEnemyKilled(); and an
event public static event OnEnemyKilled enemyKilled; in your Enemy class.
Other classes can then subscribe to the enemyKilled event and respond when
it is invoked.
• Exception handling can be useful for debugging and managing errors in
game scripts.
• Generic types in C# allows for more flexible and reusable code, such as
custom collection classes.
• Example: In a LootDrop<T> class that defines how an enemy drops loot, T
could be any type, allowing for different kinds of loot like LootDrop<Gold> or
LootDrop<Weapon>
AI FOR GAMING 19
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# and Unity3D: OOP Benefits (contd.)
• Asynchronous programming through Coroutines
• Useful for time-delayed actions, animations, and more.
• Example of Coroutine to delay a game event:
• C# in Unity is fully integrated with the Unity engine's API, allowing
scripts to control nearly every aspect of a game's behavior.
• Unity's C# scripting supports namespaces, which can be useful for
organizing large codebases and avoiding name conflicts.
• The MonoBehaviour class in Unity provides a framework for game
development, with many built-in methods like Start(), Update(),
OnCollisionEnter(), etc., that can be overridden to implement game
logic.
AI FOR GAMING 20
Yetunde Folajimi, PhD
Enumerator DelayedEvent() {
yield return new WaitForSeconds(2);
/* Event code here */
}
SCHOOL OF COMPUTING & DATA SCIENCE
C# and Unity3D: OOP Benefits (contd.)
• Unity's C# scripting supports asynchronous programming through
Coroutines, which can be used for time-delayed actions, animations, and
more.
• C# in Unity is fully integrated with the Unity engine's API, allowing scripts
to control nearly every aspect of a game's behavior.
• Unity's C# scripting supports namespaces, which can be useful for
organizing large codebases and avoiding name conflicts.
• The MonoBehaviour class in Unity provides a framework for game
development, with many built-in methods like Start(), Update(),
OnCollisionEnter(), etc., that can be overridden to implement game logic.
• Unity includes support for creating and manipulating Unity-specific types
such as Vector3, Quaternion, and Color, using C#
• In Unity, serialization is used to save and load game data, allowing for
things like game state persistence and object prefab customization.
• C# in Unity supports the use of attributes, which provide metadata about
your code and can control how it behaves in the Unity editor.
• E.g., the [SerializeField] and [Range] attributes.
AI FOR GAMING 21
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# Scripting in Unity
• Creating a New C# Script:
• Project window > Create > C# Script
• Open script in the default code editor.
• The Script Structure:
• "using" statements (optional) imports
namespaces for accessing Unity
functionality
• Class declaration contains the script's
code.
• Inherits the Monobehavior class
• Supports various methods, such as Start() and
Update(), which define the script's behavior.
AI FOR GAMING 22
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# Scripting in Unity (contd.)
• Opening the Script in an IDE:
• Recommended IDE: Visual Studio or Visual
Studio Code
• Offer advanced features like code completion,
debugging, and refactoring.
• Using the script in unity:
• Attach to any game object in the project
hierarchy
AI FOR GAMING 23
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# Scripting in Unity (contd.)
• Testing Scripts:
• Use Play Mode to test your scripts in the editor, simulating the game environment.
• Unit Testing enables writing specific tests to verify the functionality of individual script
components.
• Unity's Console panel displays error messages, warnings, and other log output.
• Debug.Log statements helps to output information to the console for debugging purposes.
• Debugging Scripts:
• Set breakpoints in your code, allowing you to pause execution at specific lines and inspect
the values of variables.
• Use the Unity Debugger to step through your code, view call stacks, and analyze runtime
behavior.
AI FOR GAMING 24
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
The MonoBehaviour Class
• MonoBehaviour is a special class in Unity used for most scripts in
Unity projects. It provides essential functionalities and integration with
the Unity engine.
• Script Lifecycle with MonoBehaviour:
• Specific lifecycle scripts managed by Unity, including methods like Awake(),
Start(), Update(), FixedUpdate(), LateUpdate(), and OnDestroy().
• Accessing Unity-specific Functionality:
• MonoBehaviour provides access to Unity-specific functionalities, such as
working with transforms, input, physics, and animations.
• Creating Custom MonoBehaviour Scripts:
• Derive them from the MonoBehaviour class and define your own behavior.
• Common Uses of MonoBehaviour:
• Player controls, enemy behaviors, animations, camera movements, and UI
interactions.
AI FOR GAMING 25
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
C# Data Types, Variables & Operators
• Basic data types: int, float, double, bool, char, string.
• int: whole numbers, e.g., -42, 0, 256.
• float: single-precision floating-point numbers, e.g., 3.14f, -0.5f.
• double: double-precision floating-point numbers, e.g., 3.14, -0.5.
• bool: true or false.
• char: single characters, e.g., 'a', 'Z', '7'.
• string: sequences of characters, e.g., "Hello, World!".
• Variables:
• Declare variables by specifying the data type and a name.
• Optionally, assign a value using the assignment operator (=)
• Operators:
• Arithmetic operators: +, -, *, /, %.
• Comparison operators: ==, !=, <, >, <=, >=.
• Logical operators: && (and), || (or), ! (not).
• Increment and decrement: ++, --.
AI FOR GAMING 26
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Example
• In this script, we declare and initialize
variables of different data types,
including int, float, and string.
• We perform various operations using
these variables.
• We store the results in separate
variables (sum, difference, product,
quotient, remainder).
• We combine the text variable with the
string " Unity" and storing it in
combinedText.
• We output the results using Debug.Log,
to display the results in the Unity
Console window.
AI FOR GAMING 27
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Control Structure, Loops, & Functions
• Control Structure:
• if, else if, and else for conditional execution.
• switch for multi-case conditional execution.
• Loops:
• for loops for iterating a fixed number of times.
• while loops for iterating as long as a condition
is true.
• foreach loops for iterating over collections.
• Functions:
• Functions are blocks of code that can be called
by name.
• Functions can accept input (parameters) and
return output (return value).
• Declare functions using the return type, name,
and parameter list.
AI FOR GAMING 28
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Exercise
• You are given an array of integers representing the scores of each
character in a game. Write a script that calculates and returns the
highest score among the characters using control structures, loops,
and a function.
AI FOR GAMING 29
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
OOP
• Classes
• Define a class using the "class" keyword.
• Declare properties (variables) and methods (functions)
within the class.
• Instantiate objects from classes using the "new"
keyword.
• Access Modifiers
• Control the visibility of class members.
• public: accessible from anywhere.
• private: accessible only within the class.
• protected: accessible within the class and its derived
classes.
• Constructors:
• Special methods called when an object is created.
• Used to initialize object properties and perform setup.
• No return type, and the name must match the class name.
AI FOR GAMING 30
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
OOP
• Inheritance
• Allows a class to inherit properties and methods from
another class.
• Use the "base" keyword to call the base class's
constructor.
• Polymorphism
• Derived classes can override or extend base class methods.
• Use the "override" keyword to redefine a method in the derived
class.
AI FOR GAMING 31
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Unity-Specific C# Features
• MonoBehaviour: base class for all Unity scripts.
• Start() and Update(): built-in methods for initialization
and frame updates.
• Input handling:
• Input.GetKey(), Input.GetMouseButtonDown(), etc.
• Accessing Unity Components
• GetComponent<T>(): access components attached to a
GameObject.
• Collision Detection and Triggers
• OnCollisionEnter(), OnCollisionExit(), OnTriggerEnter(),
OnTriggerExit().
• Respond to collisions and triggers between GameObjects.
• Coroutines
• StartCoroutine(): run a sequence of events with delays.
• IEnumerator functions with yield return new
WaitForSeconds().
AI FOR GAMING 32
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Exercise
• Create a script that allows the player to control a cube object in Unity
using the keyboard or arrow keys:
• Create a new script
• Attach the script to a cube object
• Select the cube object in the Unity scene.
• In the "Inspector" window, click "Add Component" and search for
"CubePlayerController".
• Click on "CubePlayerController" to attach the script to the cube.
• Open the script and modify it with the following code:
• Save the script and close the code editor.
• Press the "Play" button to run the scene.
• Use the keyboard or arrow keys to control the cube's movement.
• Observe how the cube responds to your input and moves accordingly.
AI FOR GAMING 33
Yetunde Folajimi, PhD
public float movementSpeed = 5f;
void Update()
{
transform.Translate(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) *
movementSpeed * Time.deltaTime);
}
SCHOOL OF COMPUTING & DATA SCIENCE
Unity-Specific C# Features (contd)
• UI Elements and Events
• - Using UnityEngine.UI namespace.
• - Accessing UI elements and updating text,
images, etc.
• - Adding listeners for button clicks and other
UI events.
• Saving and Loading Data
• - PlayerPrefs for simple data storage (int,
float, string).
• - Binary serialization and deserialization for
complex data.
• Example:
AI FOR GAMING 34
Yetunde Folajimi, PhD
// Save PlayerPrefs.SetInt("HighScore", 100); PlayerPrefs.Save();
// Load int highScore = PlayerPrefs.GetInt("HighScore", 0);
SCHOOL OF COMPUTING & DATA SCIENCE
Unity-Specific C# Features (contd)
• Networking with Unity
• Unity Networking API: High-level and low-level API.
• UNet, Photon Unity Networking (PUN), and other third-party solutions.
• Example:
• Best Practices
• - Use descriptive variable and function names.
• - Keep functions small and focused on a single task.
• - Use comments to explain complex or unclear code.
• - Organize your code into separate classes, methods, and regions.
• Resources
• - Unity Scripting API: [https://docs.unity3d.com/ScriptReference/index.html]
• - C# Programming Yellow Book: [https://www.robmiles.com/c-yellow-book/]
• - Unity Learn: [https://learn.unity.com/]
AI FOR GAMING 35
Yetunde Folajimi, PhD
using UnityEngine.Networking;
public class MyNetworkManager : NetworkManager {
// Override methods for custom networking functionality
}
SCHOOL OF COMPUTING & DATA SCIENCE
Introduction to Virtual Reality (VR)
• What is Virtual Reality?
• A technology that creates computer-generated
environments that immerse the user, simulating real or
fictional experiences.
• Computer-generated 3D environments
• Interaction through physical movement and input devices
• Immersion and Presence
• Immersion: The feeling of being physically present in a
non-physical world
• Presence: The psychological effect of immersion,
convincing the user's brain that the virtual environment is
real
• Key factors: Achieving immersion and presence requires
high-quality visual, audio, and haptic feedback that
matches the user's expectations and sensory inputs.
AI FOR GAMING 36
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
History of VR in Gaming
• VR has evolved from early experiments in the 1960s and 1970s to
the modern era with high-quality consumer VR devices like Oculus
Rift and HTC Vive.
• Early experiments in the 1960s and 1970s: Researchers started
exploring VR technology with head-mounted displays and early
motion-tracking systems.
• The rise of VR in the 1990s: VR gained attention in the gaming
industry with devices like the Virtual Boy and early arcade VR
systems.
• Modern VR gaming: Today's VR gaming landscape includes
devices like Oculus Rift, HTC Vive, and PlayStation VR, offering
high-quality experiences and a wide range of games.
AI FOR GAMING 37
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
AI FOR GAMING 38
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Types of VR systems
• Tethered VR systems: These high-end devices, such as Oculus
Rift and HTC Vive, connect to a PC or console for processing
power and graphical capabilities.
• Standalone VR systems: Devices like Oculus Quest are all-in-one
systems that don't require external connections, offering greater
portability and ease of use.
• Smartphone-based VR: Mobile devices can be used with VR
headsets like Samsung Gear VR or Google Cardboard, providing a
more affordable entry point to VR experiences.
AI FOR GAMING 39
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
VR in Unity3D
• Unity's built-in VR support: Unity provides
native support for multiple VR platforms,
making it easier to develop VR games.
• Unity supports multiple VR platforms: Develop
for various VR devices without needing to
rewrite your code for each platform.
• Automatic integration with input devices and
headsets: Unity handles integration with VR
headsets and controllers, simplifying input
management.
• Unity's XR Interaction Toolkit: This toolkit
streamlines the process of implementing VR
interactions in your game, supporting a wide
range of devices.
AI FOR GAMING 40
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
VR in Unity3D
• Importing VR packages and SDKs: To develop for specific VR
devices, import the necessary packages and SDKs, such as
Oculus Integration for Oculus devices.
• Oculus Integration package for Oculus devices: Download this package
from the Unity Asset Store to develop for Oculus devices, such as
Oculus Quest 2.
• VR SDK installation: In the Unity project, navigate to the Player Settings
and select the desired VR SDK (e.g., Oculus) under XR Settings.
• Keep SDKs updated: Ensure you have the latest versions of the
packages and SDKs to access new features and bug fixes.
AI FOR GAMING 41
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
VR in Unity3D
• Setting up a VR project: To create a VR game in Unity,
you'll need to set up a new project, install the required
packages, and configure the project for VR
development.
• Create a new Unity project: Select a 3D template to start your VR
game project.
• Install Oculus Integration package: Go to the Unity Asset Store, search
for the Oculus Integration package, and import it into your project.
• Configure XR settings: In the Unity Editor, go to Edit > Project Settings
> Player > XR Settings, enable Virtual Reality Supported, and add the
Oculus SDK.
AI FOR GAMING 42
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Oculus Quest 2 Development
• Standalone VR device: Oculus Quest 2 is a
powerful, all-in-one VR headset that doesn't require
a PC connection.
• Oculus Quest development requirements: To
develop for Oculus Quest, you'll need the Oculus
Integration package, Oculus Developer account,
and a compatible Android device (for testing).
• Oculus Developer Dashboard: Sign up for an
Oculus Developer account and access the Oculus
Developer Dashboard to manage your VR projects
and settings.
• Setting up Oculus Quest 2 for Development
• Enable Developer Mode on Oculus Quest 2: In the
Oculus app, navigate to Settings > Oculus Quest 2 >
More Settings > Developer Mode, and toggle it on.
• Connect Oculus Quest 2 to PC: Use a compatible USB
cable to connect the headset to your development PC.
• Install the Oculus ADB Drivers: Download and install the
Oculus ADB Drivers from the Oculus Developer website
to enable communication between your PC and Oculus
Quest 2.
AI FOR GAMING 43
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Developing for Oculus Quest 2 in Unity
• Set up a Unity scene for VR: Create a new Unity scene, delete the
default camera, and add an OVRCameraRig prefab from the Oculus
Integration package.
• Configure input actions: Use the Input System package or XR Interaction
Toolkit to set up input actions for the Oculus Touch controllers.
• Build and run on Oculus Quest 2: In Unity, go to File > Build Settings, add
your scene, set the target platform to Android, and click Build and Run to
test your game on Oculus Quest 2.
• Implementing VR Interactions
• Types of VR interactions: Common VR interactions include grabbing, throwing,
teleporting, and using tools or weapons.
• XR Interaction Toolkit: Unity's XR Interaction Toolkit provides a framework
for implementing various VR interactions in your game.
• Customizing interactions with C# scripts: Write C# scripts to customize and
extend the functionality of VR interactions provided by the XR Interaction
Toolkit.
AI FOR GAMING 44
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Developing for Oculus Quest 2 in Unity
• Implementing Grabbing and Throwing
• XR Grab Interactable: Attach this component to
objects that the player can grab and throw.
• XR Direct Interactor: Add this component to the
controller objects to enable grabbing and throwing
interactions.
• Customizing grabbing and throwing: Write C# scripts
to modify how objects behave when they're grabbed,
thrown, or interacted with in other ways.
• Implementing Teleportation
• XR Teleportation Provider: Attach this component to
the XR Rig to enable teleportation.
• XR Teleportation Interactable: Add this component to
a controller object to allow the player to initiate
teleportation.
• Customizing teleportation: Use C# scripts to
change the behavior, appearance, or functionality
of teleportation in your game.
AI FOR GAMING 45
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Developing for Oculus Quest 2 in Unity
• Implementing Tools and Weapons
• XR Base Interactable: Use this base class to create custom interactable
objects, such as tools and weapons.
• XR Ray Interactor: Attach this component to a controller object to enable ray-
based interactions with objects in the scene.
• Customizing tools and weapons: Write C# scripts to create unique behaviors
and interactions for tools and weapons, such as firing projectiles or swinging a
sword.
• Testing and Debugging VR Games
• Play mode in Unity Editor: Test and debug your game directly in the Unity
Editor using Play mode. For Oculus Quest 2, you can use the Oculus Link
feature to connect the headset to your PC.
• Build and run on target device: Regularly test your game on the target VR
device, such as Oculus Quest 2, to ensure that it performs well and provides a
comfortable experience.
• Performance optimization: Optimize your game for VR by managing CPU,
GPU, and memory usage, ensuring a smooth and comfortable experience for
players.
AI FOR GAMING 46
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Developing for Oculus Quest 2 in Unity
• Implementing Tools and Weapons
• XR Base Interactable: Use this base class to create custom interactable
objects, such as tools and weapons.
• XR Ray Interactor: Attach this component to a controller object to enable ray-
based interactions with objects in the scene.
• Customizing tools and weapons: Write C# scripts to create unique behaviors
and interactions for tools and weapons, such as firing projectiles or swinging a
sword.
• Testing and Debugging VR Games
• Play mode in Unity Editor: Test and debug your game directly in the Unity
Editor using Play mode. For Oculus Quest 2, you can use the Oculus Link
feature to connect the headset to your PC.
• Build and run on target device: Regularly test your game on the target VR
device, such as Oculus Quest 2, to ensure that it performs well and provides a
comfortable experience.
• Performance optimization: Optimize your game for VR by managing CPU,
GPU, and memory usage, ensuring a smooth and comfortable experience for
players.
AI FOR GAMING 47
Yetunde Folajimi, PhD
SCHOOL OF COMPUTING & DATA SCIENCE
Summary
• C# is a powerful, versatile, and object-oriented programming
language.
• Essential C# concepts include syntax, data types, variables,
operators, control structures, loops, and functions.
• Object-oriented programming concepts such as classes, inheritance, and
polymorphism are important in C#.
• Unity-specific C# features include MonoBehaviour, Start(), Update(), Input
handling, accessing components, collision detection, triggers, coroutines, UI
elements, events, data saving, and networking.
• Good programming practices improve code readability, maintainability, and
overall project quality.
• Now that you have a comprehensive understanding of C#
programming basics with Unity3D, you'll be well-equipped to start
creating your own games and applications in Unity. Remember to
refer back to these slides and the provided resources as you continue
learning and growing as a developer.
AI FOR GAMING 48
Yetunde Folajimi, PhD

More Related Content

Similar to AI For Gaming lecture2 Unity and c# basics.pdf (20)

PPTX
Game development -session on unity 3d
Muhammad Maaz Irfan
 
PDF
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
PDF
Introduction to Unity by Purdue university
asdf936939
 
PPTX
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
PPTX
Creating great Unity games for Windows 10 - Part 1
Jiri Danihelka
 
PDF
Unity Tutorial_Highlighted Notes.pdf
Arumugam90
 
PDF
Let's make a game unity
Saija Ketola
 
PPTX
Unity 3D VS your team
Christoph Becher
 
PPTX
WIG3004 virtual reality chapter3 software.pptx
GarethNg8
 
PDF
Lecture 1 Introduction to VR Programming
Kobkrit Viriyayudhakorn
 
PDF
Mobile AR Lecture6 - Introduction to Unity 3D
Mark Billinghurst
 
PPTX
What Are The Reasons Behind Unity 3 D’s Popularity For Games - BR Softech
B R SOFTECH PVT LTD
 
PPTX
Unity 3D
gema123
 
PPTX
Computer Game Design
Sadia Zafar
 
PPTX
Game Development with Unity
davidluzgouveia
 
PDF
Deploy All The Games
Adam Hill
 
PPTX
Introduction to Unity
University of Auckland
 
PPTX
Unity Game Engine Presentation for ICT..
MerryGoldCuestas
 
PDF
Game Models - A Different Approach
Nick Pruehs
 
PDF
Unity 3D Flexible Software for Real-Time Applications.pdf
Vdoit Technologies
 
Game development -session on unity 3d
Muhammad Maaz Irfan
 
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Introduction to Unity by Purdue university
asdf936939
 
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Creating great Unity games for Windows 10 - Part 1
Jiri Danihelka
 
Unity Tutorial_Highlighted Notes.pdf
Arumugam90
 
Let's make a game unity
Saija Ketola
 
Unity 3D VS your team
Christoph Becher
 
WIG3004 virtual reality chapter3 software.pptx
GarethNg8
 
Lecture 1 Introduction to VR Programming
Kobkrit Viriyayudhakorn
 
Mobile AR Lecture6 - Introduction to Unity 3D
Mark Billinghurst
 
What Are The Reasons Behind Unity 3 D’s Popularity For Games - BR Softech
B R SOFTECH PVT LTD
 
Unity 3D
gema123
 
Computer Game Design
Sadia Zafar
 
Game Development with Unity
davidluzgouveia
 
Deploy All The Games
Adam Hill
 
Introduction to Unity
University of Auckland
 
Unity Game Engine Presentation for ICT..
MerryGoldCuestas
 
Game Models - A Different Approach
Nick Pruehs
 
Unity 3D Flexible Software for Real-Time Applications.pdf
Vdoit Technologies
 

Recently uploaded (20)

PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Digital Circuits, important subject in CS
contactparinay1
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Ad

AI For Gaming lecture2 Unity and c# basics.pdf

  • 1. SCHOOL OF COMPUTING & DATA SCIENCE AI For Gaming Yetunde Folajimi, Ph.D.
  • 2. SCHOOL OF COMPUTING & DATA SCIENCE Lecture 2: AI FOR GAMING 2 Yetunde Folajimi, PhD Unity3D & C# Basics
  • 3. SCHOOL OF COMPUTING & DATA SCIENCE What is Unity3D? • Unity3D is a powerful, cross-platform game engine and development environment. • Widely used in the gaming industry for creating 2D and 3D games and experiences. • Supports a variety of platforms, including PC, console, mobile, and virtual reality. AI FOR GAMING 3 Yetunde Folajimi, PhD
  • 4. SCHOOL OF COMPUTING & DATA SCIENCE What is Unity3D? (contd.) • Features: • Integrated development environment (IDE) with user-friendly interface. • Visual scene editor for creating and editing game objects. • Powerful scripting support using C#. • Asset management and import system. • The Unity Ecosystem: • Unity Asset Store: A marketplace for game assets, tools, and plugins. • https://assetstore.unity.com/ • Unity Services: Cloud-based solutions for building, testing, and monetizing games. • Unity Learn: A platform offering tutorials, courses, and learning resources. • https://learn.unity.com/ • Unity Community: Forums, blogs, and events for Unity developers. • https://unity.com/community AI FOR GAMING 4 Yetunde Folajimi, PhD
  • 5. SCHOOL OF COMPUTING & DATA SCIENCE Installing Unity3D with UnityHub • Visit Unity's official website to download the Unity Hub: https://unity.com/ • Unity Hub: A central application for managing Unity installations and projects. • Create or sign in to your Unity account. • Select the appropriate version of Unity for your needs. • Choose the platforms and modules you want to install. • Creating a New Project: • Open Unity Hub and click on the "New" button. • Choose a project template (2D, 3D, or other templates). • Name your project and choose a location to save it. • Click "Create" to start your new Unity project. AI FOR GAMING 5 Yetunde Folajimi, PhD
  • 6. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D Interface • Key panels: Scene, Game, Hierarchy, Project, and Inspector. • Customizable layout to fit your preferences. AI FOR GAMING 6 Yetunde Folajimi, PhD
  • 7. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D Interface • (A) The Toolbar provides access to your Unity Account and Unity Cloud Services. It also contains controls for Play mode; Unity Search; a layer visibility menu; and the Editor layout menu. • (B) Hierarchy panel: • Lists all game objects in the current scene. • Organize game objects using parent-child relationships and groups. • Select, add, or remove game objects from the scene. AI FOR GAMING 7 Yetunde Folajimi, PhD
  • 8. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D Interface • (C) Game View: Displays your game as it would appear when played • Test and debug your game directly within the Unity editor • Aspect ratio and resolution options for different devices. • (D) Scene View: The region where you create and edit game objects in your game. • Navigation and manipulation tools for moving, rotating, and scaling objects. • Grid and gizmos for easier placement and alignment. AI FOR GAMING 8 Yetunde Folajimi, PhD
  • 9. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D Interface • (E) Overlays contain the basic tools for manipulating the Scene view and the GameObjects within it. You can also add custom Overlays to improve your workflow. • (F) Inspector Panel: • Modify properties and settings of selected game objects. • Add, remove, or edit components attached to game objects (e.g., scripts, colliders, renderers). AI FOR GAMING 9 Yetunde Folajimi, PhD
  • 10. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D Interface • (G) Project panel: • Displays all assets and folders in your Unity project. • Import and manage game assets, such as textures, models, sounds, and scripts. • Create and organize folders to keep your project organized. • (H) The status bar provides notifications about various Unity processes, and quick access to related tools and settings. AI FOR GAMING 10 Yetunde Folajimi, PhD
  • 11. SCHOOL OF COMPUTING & DATA SCIENCE Working with the Unity Engine • Inspector Panel: • Modify properties and settings of selected game objects. • Add, remove, or edit components attached to game objects (e.g., scripts, colliders, renderers). • Creating Game Objects • Create game objects using the GameObject menu or right-clicking in the Hierarchy panel. • Basic game objects: Empty, 3D Object (Cube, Sphere, etc.), 2D Object (Sprite), Light, Camera, and more. • Game objects can be combined and customized to create complex scenes. • Importing Assets • Import assets by dragging and dropping files into the Project panel or using the Assets > Import menu. • Supported file formats: FBX, OBJ (3D models), PNG, JPG (textures), MP3, WAV (audio), and more. • Unity Asset Store: Download and import assets directly into your project. AI FOR GAMING 11 Yetunde Folajimi, PhD
  • 12. SCHOOL OF COMPUTING & DATA SCIENCE Working with the Unity Engine (contd.) • Scripting in Unity: • Unity supports C# scripting for game logic and interactivity. • Create a new script from the Assets menu or by right- clicking in the Project panel. • Scripts can be attached to game objects as components. • Unity Scripting API • Unity provides a rich scripting API for accessing and manipulating game objects and components. • Common namespaces: • UnityEngine (core functionality) • UnityEngine.AI (Implements Unity pathfinding features) • UnityEngine.Analytics (collects core events and user properties) • UnityEngine.SceneManagement (scene management functionalities). • Documentation: https://docs.unity3d.com/ScriptReference/ AI FOR GAMING 12 Yetunde Folajimi, PhD
  • 13. SCHOOL OF COMPUTING & DATA SCIENCE Working with the Unity Engine (contd.) • Building and Running Your Game • Build and run your game using the File > Build Settings menu. • Choose the target platform and adjust build settings as needed. • Click "Build and Run" to create an executable and launch your game. • Testing and Debugging • Test your game directly in the Unity editor using the Play button in the Game View. • Unity's Console panel displays error messages, warnings, and other log output. • Debug.Log() function can be used in scripts to output messages to the Console. AI FOR GAMING 13 Yetunde Folajimi, PhD
  • 14. SCHOOL OF COMPUTING & DATA SCIENCE Working with the Unity Engine (contd.) • Learning Resources: • Unity manual: https://docs.unity3d.com/Manual/ • Unity Scripting Reference: https://docs.unity3d.com/ScriptReference/ • Unity Learn: https://learn.unity.com/ • Official Unity tutorials: https://unity3d.com/learn/tutorials • Unity YouTube channel: https://www.youtube.com/user/Unity3D • Unity Collaborate: • A built-in version control system for working with teams. • Enable Collaborate in the Unity Services window (Window > Unity Services). • Invite team members, manage project versions, and resolve conflicts. • Community and Support • Unity forums: https://forum.unity.com/ • Unity Answers: https://answers.unity.com/ • Unity Asset Store support: https://unity3d.com/asset-store • Tutorials and Sample Projects • Roll-a-Ball, Space Shooter, Survival Shooter, 2D Roguelike, and more. • Access these resources through the Unity Learn platform or download them from the Asset Store. AI FOR GAMING 14 Yetunde Folajimi, PhD
  • 15. SCHOOL OF COMPUTING & DATA SCIENCE Introduction to C# • C# is a powerful, versatile, and object-oriented programming language. • Developed by Microsoft as part of the .NET framework. • Widely used in the software industry and a primary language for Unity3D development. • Easy to learn for beginners, with a syntax similar to Java and C++ • C# documentation: https://learn.microsoft.com/en-us/dotnet/csharp/ • C# Syntax Basics • Statements end with a semicolon (;). • Curly braces ({}) define blocks of code. • Variables must be declared with a type before use. • Comments: single line (//) and multi-line (/* ... */). AI FOR GAMING 15 Yetunde Folajimi, PhD
  • 16. SCHOOL OF COMPUTING & DATA SCIENCE C# and Unity3D • Accessing Unity Components: • Unity provides various components (e.g., transform, rigidbody) that define the properties and behavior of game objects. In C# scripts, you can access and manipulate these components to modify the objects in your game. • Event Handling: • Events are actions or occurrences that happen during gameplay, such as a button click or collision. You can handle events in C# scripts to trigger specific actions or behaviors in response to these events. • Script Execution Order: • By default, scripts are executed in the order they are loaded, but you can modify the execution order using script execution order attributes to ensure correct dependencies and interactions. AI FOR GAMING 16 Yetunde Folajimi, PhD
  • 17. SCHOOL OF COMPUTING & DATA SCIENCE C# and Unity3D (contd.) • Attaching Scripts to Game Objects: • Select the desired object in the Unity Scene view or Hierarchy window. • In the Inspector window, click on the "Add Component" button and search for the script name. • Select the script to attach it to the game object. • Communicating Between Scripts and Game Objects: • Use public variables in the script that can be accessed and modified by other scripts or the Unity Editor, or • Use events or Unity's messaging system to send messages between scripts and game objects. • Script Best Practices: • Organize your code • Use meaningful variable and method names, • Comment your code, • Optimizing performance-intensive operations. AI FOR GAMING 17 Yetunde Folajimi, PhD
  • 18. SCHOOL OF COMPUTING & DATA SCIENCE Unity3D & C#: OOP Benefits • Inheritance allows one class to inherit the fields and methods of another class, which can be useful for creating more specialized game objects. • Example: A base class Enemy that has general methods like TakeDamage() could have a Zombie class that inherits from Enemy and overrides the TakeDamage() method to include zombie-specific behavior. • Polymorphism allows developers to use methods from a base class, but define different implementations for those methods in derived classes. • Example: For a method in the game manager that accepts an Enemy object and calls TakeDamage(). You could pass in a Zombie object and, thanks to polymorphism, the Zombie version of TakeDamage() would be called. • Encapsulation protects the internal state and functionality of game objects. • In a Player class with a private health field. Use a public method like TakeDamage(int damage) to control how health is reduced, rather than allowing other classes to change health directly. AI FOR GAMING 18 Yetunde Folajimi, PhD
  • 19. SCHOOL OF COMPUTING & DATA SCIENCE C# and Unity3D: OOP Benefits (Contd.) • Event-driven programming model allows game objects to respond to a variety of input or events, such as mouse clicks or button presses. Delegates can be used to create and control events, which are often used for creating game logic. • Example: Define a delegate public delegate void OnEnemyKilled(); and an event public static event OnEnemyKilled enemyKilled; in your Enemy class. Other classes can then subscribe to the enemyKilled event and respond when it is invoked. • Exception handling can be useful for debugging and managing errors in game scripts. • Generic types in C# allows for more flexible and reusable code, such as custom collection classes. • Example: In a LootDrop<T> class that defines how an enemy drops loot, T could be any type, allowing for different kinds of loot like LootDrop<Gold> or LootDrop<Weapon> AI FOR GAMING 19 Yetunde Folajimi, PhD
  • 20. SCHOOL OF COMPUTING & DATA SCIENCE C# and Unity3D: OOP Benefits (contd.) • Asynchronous programming through Coroutines • Useful for time-delayed actions, animations, and more. • Example of Coroutine to delay a game event: • C# in Unity is fully integrated with the Unity engine's API, allowing scripts to control nearly every aspect of a game's behavior. • Unity's C# scripting supports namespaces, which can be useful for organizing large codebases and avoiding name conflicts. • The MonoBehaviour class in Unity provides a framework for game development, with many built-in methods like Start(), Update(), OnCollisionEnter(), etc., that can be overridden to implement game logic. AI FOR GAMING 20 Yetunde Folajimi, PhD Enumerator DelayedEvent() { yield return new WaitForSeconds(2); /* Event code here */ }
  • 21. SCHOOL OF COMPUTING & DATA SCIENCE C# and Unity3D: OOP Benefits (contd.) • Unity's C# scripting supports asynchronous programming through Coroutines, which can be used for time-delayed actions, animations, and more. • C# in Unity is fully integrated with the Unity engine's API, allowing scripts to control nearly every aspect of a game's behavior. • Unity's C# scripting supports namespaces, which can be useful for organizing large codebases and avoiding name conflicts. • The MonoBehaviour class in Unity provides a framework for game development, with many built-in methods like Start(), Update(), OnCollisionEnter(), etc., that can be overridden to implement game logic. • Unity includes support for creating and manipulating Unity-specific types such as Vector3, Quaternion, and Color, using C# • In Unity, serialization is used to save and load game data, allowing for things like game state persistence and object prefab customization. • C# in Unity supports the use of attributes, which provide metadata about your code and can control how it behaves in the Unity editor. • E.g., the [SerializeField] and [Range] attributes. AI FOR GAMING 21 Yetunde Folajimi, PhD
  • 22. SCHOOL OF COMPUTING & DATA SCIENCE C# Scripting in Unity • Creating a New C# Script: • Project window > Create > C# Script • Open script in the default code editor. • The Script Structure: • "using" statements (optional) imports namespaces for accessing Unity functionality • Class declaration contains the script's code. • Inherits the Monobehavior class • Supports various methods, such as Start() and Update(), which define the script's behavior. AI FOR GAMING 22 Yetunde Folajimi, PhD
  • 23. SCHOOL OF COMPUTING & DATA SCIENCE C# Scripting in Unity (contd.) • Opening the Script in an IDE: • Recommended IDE: Visual Studio or Visual Studio Code • Offer advanced features like code completion, debugging, and refactoring. • Using the script in unity: • Attach to any game object in the project hierarchy AI FOR GAMING 23 Yetunde Folajimi, PhD
  • 24. SCHOOL OF COMPUTING & DATA SCIENCE C# Scripting in Unity (contd.) • Testing Scripts: • Use Play Mode to test your scripts in the editor, simulating the game environment. • Unit Testing enables writing specific tests to verify the functionality of individual script components. • Unity's Console panel displays error messages, warnings, and other log output. • Debug.Log statements helps to output information to the console for debugging purposes. • Debugging Scripts: • Set breakpoints in your code, allowing you to pause execution at specific lines and inspect the values of variables. • Use the Unity Debugger to step through your code, view call stacks, and analyze runtime behavior. AI FOR GAMING 24 Yetunde Folajimi, PhD
  • 25. SCHOOL OF COMPUTING & DATA SCIENCE The MonoBehaviour Class • MonoBehaviour is a special class in Unity used for most scripts in Unity projects. It provides essential functionalities and integration with the Unity engine. • Script Lifecycle with MonoBehaviour: • Specific lifecycle scripts managed by Unity, including methods like Awake(), Start(), Update(), FixedUpdate(), LateUpdate(), and OnDestroy(). • Accessing Unity-specific Functionality: • MonoBehaviour provides access to Unity-specific functionalities, such as working with transforms, input, physics, and animations. • Creating Custom MonoBehaviour Scripts: • Derive them from the MonoBehaviour class and define your own behavior. • Common Uses of MonoBehaviour: • Player controls, enemy behaviors, animations, camera movements, and UI interactions. AI FOR GAMING 25 Yetunde Folajimi, PhD
  • 26. SCHOOL OF COMPUTING & DATA SCIENCE C# Data Types, Variables & Operators • Basic data types: int, float, double, bool, char, string. • int: whole numbers, e.g., -42, 0, 256. • float: single-precision floating-point numbers, e.g., 3.14f, -0.5f. • double: double-precision floating-point numbers, e.g., 3.14, -0.5. • bool: true or false. • char: single characters, e.g., 'a', 'Z', '7'. • string: sequences of characters, e.g., "Hello, World!". • Variables: • Declare variables by specifying the data type and a name. • Optionally, assign a value using the assignment operator (=) • Operators: • Arithmetic operators: +, -, *, /, %. • Comparison operators: ==, !=, <, >, <=, >=. • Logical operators: && (and), || (or), ! (not). • Increment and decrement: ++, --. AI FOR GAMING 26 Yetunde Folajimi, PhD
  • 27. SCHOOL OF COMPUTING & DATA SCIENCE Example • In this script, we declare and initialize variables of different data types, including int, float, and string. • We perform various operations using these variables. • We store the results in separate variables (sum, difference, product, quotient, remainder). • We combine the text variable with the string " Unity" and storing it in combinedText. • We output the results using Debug.Log, to display the results in the Unity Console window. AI FOR GAMING 27 Yetunde Folajimi, PhD
  • 28. SCHOOL OF COMPUTING & DATA SCIENCE Control Structure, Loops, & Functions • Control Structure: • if, else if, and else for conditional execution. • switch for multi-case conditional execution. • Loops: • for loops for iterating a fixed number of times. • while loops for iterating as long as a condition is true. • foreach loops for iterating over collections. • Functions: • Functions are blocks of code that can be called by name. • Functions can accept input (parameters) and return output (return value). • Declare functions using the return type, name, and parameter list. AI FOR GAMING 28 Yetunde Folajimi, PhD
  • 29. SCHOOL OF COMPUTING & DATA SCIENCE Exercise • You are given an array of integers representing the scores of each character in a game. Write a script that calculates and returns the highest score among the characters using control structures, loops, and a function. AI FOR GAMING 29 Yetunde Folajimi, PhD
  • 30. SCHOOL OF COMPUTING & DATA SCIENCE OOP • Classes • Define a class using the "class" keyword. • Declare properties (variables) and methods (functions) within the class. • Instantiate objects from classes using the "new" keyword. • Access Modifiers • Control the visibility of class members. • public: accessible from anywhere. • private: accessible only within the class. • protected: accessible within the class and its derived classes. • Constructors: • Special methods called when an object is created. • Used to initialize object properties and perform setup. • No return type, and the name must match the class name. AI FOR GAMING 30 Yetunde Folajimi, PhD
  • 31. SCHOOL OF COMPUTING & DATA SCIENCE OOP • Inheritance • Allows a class to inherit properties and methods from another class. • Use the "base" keyword to call the base class's constructor. • Polymorphism • Derived classes can override or extend base class methods. • Use the "override" keyword to redefine a method in the derived class. AI FOR GAMING 31 Yetunde Folajimi, PhD
  • 32. SCHOOL OF COMPUTING & DATA SCIENCE Unity-Specific C# Features • MonoBehaviour: base class for all Unity scripts. • Start() and Update(): built-in methods for initialization and frame updates. • Input handling: • Input.GetKey(), Input.GetMouseButtonDown(), etc. • Accessing Unity Components • GetComponent<T>(): access components attached to a GameObject. • Collision Detection and Triggers • OnCollisionEnter(), OnCollisionExit(), OnTriggerEnter(), OnTriggerExit(). • Respond to collisions and triggers between GameObjects. • Coroutines • StartCoroutine(): run a sequence of events with delays. • IEnumerator functions with yield return new WaitForSeconds(). AI FOR GAMING 32 Yetunde Folajimi, PhD
  • 33. SCHOOL OF COMPUTING & DATA SCIENCE Exercise • Create a script that allows the player to control a cube object in Unity using the keyboard or arrow keys: • Create a new script • Attach the script to a cube object • Select the cube object in the Unity scene. • In the "Inspector" window, click "Add Component" and search for "CubePlayerController". • Click on "CubePlayerController" to attach the script to the cube. • Open the script and modify it with the following code: • Save the script and close the code editor. • Press the "Play" button to run the scene. • Use the keyboard or arrow keys to control the cube's movement. • Observe how the cube responds to your input and moves accordingly. AI FOR GAMING 33 Yetunde Folajimi, PhD public float movementSpeed = 5f; void Update() { transform.Translate(new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) * movementSpeed * Time.deltaTime); }
  • 34. SCHOOL OF COMPUTING & DATA SCIENCE Unity-Specific C# Features (contd) • UI Elements and Events • - Using UnityEngine.UI namespace. • - Accessing UI elements and updating text, images, etc. • - Adding listeners for button clicks and other UI events. • Saving and Loading Data • - PlayerPrefs for simple data storage (int, float, string). • - Binary serialization and deserialization for complex data. • Example: AI FOR GAMING 34 Yetunde Folajimi, PhD // Save PlayerPrefs.SetInt("HighScore", 100); PlayerPrefs.Save(); // Load int highScore = PlayerPrefs.GetInt("HighScore", 0);
  • 35. SCHOOL OF COMPUTING & DATA SCIENCE Unity-Specific C# Features (contd) • Networking with Unity • Unity Networking API: High-level and low-level API. • UNet, Photon Unity Networking (PUN), and other third-party solutions. • Example: • Best Practices • - Use descriptive variable and function names. • - Keep functions small and focused on a single task. • - Use comments to explain complex or unclear code. • - Organize your code into separate classes, methods, and regions. • Resources • - Unity Scripting API: [https://docs.unity3d.com/ScriptReference/index.html] • - C# Programming Yellow Book: [https://www.robmiles.com/c-yellow-book/] • - Unity Learn: [https://learn.unity.com/] AI FOR GAMING 35 Yetunde Folajimi, PhD using UnityEngine.Networking; public class MyNetworkManager : NetworkManager { // Override methods for custom networking functionality }
  • 36. SCHOOL OF COMPUTING & DATA SCIENCE Introduction to Virtual Reality (VR) • What is Virtual Reality? • A technology that creates computer-generated environments that immerse the user, simulating real or fictional experiences. • Computer-generated 3D environments • Interaction through physical movement and input devices • Immersion and Presence • Immersion: The feeling of being physically present in a non-physical world • Presence: The psychological effect of immersion, convincing the user's brain that the virtual environment is real • Key factors: Achieving immersion and presence requires high-quality visual, audio, and haptic feedback that matches the user's expectations and sensory inputs. AI FOR GAMING 36 Yetunde Folajimi, PhD
  • 37. SCHOOL OF COMPUTING & DATA SCIENCE History of VR in Gaming • VR has evolved from early experiments in the 1960s and 1970s to the modern era with high-quality consumer VR devices like Oculus Rift and HTC Vive. • Early experiments in the 1960s and 1970s: Researchers started exploring VR technology with head-mounted displays and early motion-tracking systems. • The rise of VR in the 1990s: VR gained attention in the gaming industry with devices like the Virtual Boy and early arcade VR systems. • Modern VR gaming: Today's VR gaming landscape includes devices like Oculus Rift, HTC Vive, and PlayStation VR, offering high-quality experiences and a wide range of games. AI FOR GAMING 37 Yetunde Folajimi, PhD
  • 38. SCHOOL OF COMPUTING & DATA SCIENCE AI FOR GAMING 38 Yetunde Folajimi, PhD
  • 39. SCHOOL OF COMPUTING & DATA SCIENCE Types of VR systems • Tethered VR systems: These high-end devices, such as Oculus Rift and HTC Vive, connect to a PC or console for processing power and graphical capabilities. • Standalone VR systems: Devices like Oculus Quest are all-in-one systems that don't require external connections, offering greater portability and ease of use. • Smartphone-based VR: Mobile devices can be used with VR headsets like Samsung Gear VR or Google Cardboard, providing a more affordable entry point to VR experiences. AI FOR GAMING 39 Yetunde Folajimi, PhD
  • 40. SCHOOL OF COMPUTING & DATA SCIENCE VR in Unity3D • Unity's built-in VR support: Unity provides native support for multiple VR platforms, making it easier to develop VR games. • Unity supports multiple VR platforms: Develop for various VR devices without needing to rewrite your code for each platform. • Automatic integration with input devices and headsets: Unity handles integration with VR headsets and controllers, simplifying input management. • Unity's XR Interaction Toolkit: This toolkit streamlines the process of implementing VR interactions in your game, supporting a wide range of devices. AI FOR GAMING 40 Yetunde Folajimi, PhD
  • 41. SCHOOL OF COMPUTING & DATA SCIENCE VR in Unity3D • Importing VR packages and SDKs: To develop for specific VR devices, import the necessary packages and SDKs, such as Oculus Integration for Oculus devices. • Oculus Integration package for Oculus devices: Download this package from the Unity Asset Store to develop for Oculus devices, such as Oculus Quest 2. • VR SDK installation: In the Unity project, navigate to the Player Settings and select the desired VR SDK (e.g., Oculus) under XR Settings. • Keep SDKs updated: Ensure you have the latest versions of the packages and SDKs to access new features and bug fixes. AI FOR GAMING 41 Yetunde Folajimi, PhD
  • 42. SCHOOL OF COMPUTING & DATA SCIENCE VR in Unity3D • Setting up a VR project: To create a VR game in Unity, you'll need to set up a new project, install the required packages, and configure the project for VR development. • Create a new Unity project: Select a 3D template to start your VR game project. • Install Oculus Integration package: Go to the Unity Asset Store, search for the Oculus Integration package, and import it into your project. • Configure XR settings: In the Unity Editor, go to Edit > Project Settings > Player > XR Settings, enable Virtual Reality Supported, and add the Oculus SDK. AI FOR GAMING 42 Yetunde Folajimi, PhD
  • 43. SCHOOL OF COMPUTING & DATA SCIENCE Oculus Quest 2 Development • Standalone VR device: Oculus Quest 2 is a powerful, all-in-one VR headset that doesn't require a PC connection. • Oculus Quest development requirements: To develop for Oculus Quest, you'll need the Oculus Integration package, Oculus Developer account, and a compatible Android device (for testing). • Oculus Developer Dashboard: Sign up for an Oculus Developer account and access the Oculus Developer Dashboard to manage your VR projects and settings. • Setting up Oculus Quest 2 for Development • Enable Developer Mode on Oculus Quest 2: In the Oculus app, navigate to Settings > Oculus Quest 2 > More Settings > Developer Mode, and toggle it on. • Connect Oculus Quest 2 to PC: Use a compatible USB cable to connect the headset to your development PC. • Install the Oculus ADB Drivers: Download and install the Oculus ADB Drivers from the Oculus Developer website to enable communication between your PC and Oculus Quest 2. AI FOR GAMING 43 Yetunde Folajimi, PhD
  • 44. SCHOOL OF COMPUTING & DATA SCIENCE Developing for Oculus Quest 2 in Unity • Set up a Unity scene for VR: Create a new Unity scene, delete the default camera, and add an OVRCameraRig prefab from the Oculus Integration package. • Configure input actions: Use the Input System package or XR Interaction Toolkit to set up input actions for the Oculus Touch controllers. • Build and run on Oculus Quest 2: In Unity, go to File > Build Settings, add your scene, set the target platform to Android, and click Build and Run to test your game on Oculus Quest 2. • Implementing VR Interactions • Types of VR interactions: Common VR interactions include grabbing, throwing, teleporting, and using tools or weapons. • XR Interaction Toolkit: Unity's XR Interaction Toolkit provides a framework for implementing various VR interactions in your game. • Customizing interactions with C# scripts: Write C# scripts to customize and extend the functionality of VR interactions provided by the XR Interaction Toolkit. AI FOR GAMING 44 Yetunde Folajimi, PhD
  • 45. SCHOOL OF COMPUTING & DATA SCIENCE Developing for Oculus Quest 2 in Unity • Implementing Grabbing and Throwing • XR Grab Interactable: Attach this component to objects that the player can grab and throw. • XR Direct Interactor: Add this component to the controller objects to enable grabbing and throwing interactions. • Customizing grabbing and throwing: Write C# scripts to modify how objects behave when they're grabbed, thrown, or interacted with in other ways. • Implementing Teleportation • XR Teleportation Provider: Attach this component to the XR Rig to enable teleportation. • XR Teleportation Interactable: Add this component to a controller object to allow the player to initiate teleportation. • Customizing teleportation: Use C# scripts to change the behavior, appearance, or functionality of teleportation in your game. AI FOR GAMING 45 Yetunde Folajimi, PhD
  • 46. SCHOOL OF COMPUTING & DATA SCIENCE Developing for Oculus Quest 2 in Unity • Implementing Tools and Weapons • XR Base Interactable: Use this base class to create custom interactable objects, such as tools and weapons. • XR Ray Interactor: Attach this component to a controller object to enable ray- based interactions with objects in the scene. • Customizing tools and weapons: Write C# scripts to create unique behaviors and interactions for tools and weapons, such as firing projectiles or swinging a sword. • Testing and Debugging VR Games • Play mode in Unity Editor: Test and debug your game directly in the Unity Editor using Play mode. For Oculus Quest 2, you can use the Oculus Link feature to connect the headset to your PC. • Build and run on target device: Regularly test your game on the target VR device, such as Oculus Quest 2, to ensure that it performs well and provides a comfortable experience. • Performance optimization: Optimize your game for VR by managing CPU, GPU, and memory usage, ensuring a smooth and comfortable experience for players. AI FOR GAMING 46 Yetunde Folajimi, PhD
  • 47. SCHOOL OF COMPUTING & DATA SCIENCE Developing for Oculus Quest 2 in Unity • Implementing Tools and Weapons • XR Base Interactable: Use this base class to create custom interactable objects, such as tools and weapons. • XR Ray Interactor: Attach this component to a controller object to enable ray- based interactions with objects in the scene. • Customizing tools and weapons: Write C# scripts to create unique behaviors and interactions for tools and weapons, such as firing projectiles or swinging a sword. • Testing and Debugging VR Games • Play mode in Unity Editor: Test and debug your game directly in the Unity Editor using Play mode. For Oculus Quest 2, you can use the Oculus Link feature to connect the headset to your PC. • Build and run on target device: Regularly test your game on the target VR device, such as Oculus Quest 2, to ensure that it performs well and provides a comfortable experience. • Performance optimization: Optimize your game for VR by managing CPU, GPU, and memory usage, ensuring a smooth and comfortable experience for players. AI FOR GAMING 47 Yetunde Folajimi, PhD
  • 48. SCHOOL OF COMPUTING & DATA SCIENCE Summary • C# is a powerful, versatile, and object-oriented programming language. • Essential C# concepts include syntax, data types, variables, operators, control structures, loops, and functions. • Object-oriented programming concepts such as classes, inheritance, and polymorphism are important in C#. • Unity-specific C# features include MonoBehaviour, Start(), Update(), Input handling, accessing components, collision detection, triggers, coroutines, UI elements, events, data saving, and networking. • Good programming practices improve code readability, maintainability, and overall project quality. • Now that you have a comprehensive understanding of C# programming basics with Unity3D, you'll be well-equipped to start creating your own games and applications in Unity. Remember to refer back to these slides and the provided resources as you continue learning and growing as a developer. AI FOR GAMING 48 Yetunde Folajimi, PhD