Module 3
Module 3
Visual continuity in tiles refers to ensuring that adjacent tiles in a Tilemap blend seamlessly
without noticeable gaps, abrupt edges, or mismatches. It is crucial for creating a smooth and
immersive game world where the environment looks natural and coherent rather than
disconnected or artificial.
Problem: Some tiles may have sharp edges or visible seams, breaking visual flow.
Solution: Use seamless textures where tile borders naturally connect without visible
lines.
Problem: A repeated tile pattern can make the environment look artificial.
Solution: Create multiple variations of the same tile (e.g., different grass textures)
and use Rule Tiles to distribute them randomly.
Problem: Abrupt changes between different tiles (e.g., grass to sand) can look
unnatural.
Solution: Use Blend Tiles or Auto Tiling to create smooth transitions.
Rule Tiles automatically select the correct tile variation based on adjacent tiles.
Prevents mismatches and ensures smooth transitions.
Blend tiles create smooth transitions between different terrains (e.g., grass fading into
dirt).
Use multiple sorting layers to create foreground and background elements that add
depth.
Conclusion
Visual continuity in tiles in Unity 2D ensures that the game world looks natural, immersive,
and free of distracting seams or repetitions. Using Rule Tiles, seamless textures, blend tiles,
and proper alignment, you can create a visually smooth and cohesive environment for your
game.
Adding Objects to a Scene in Unity 2D
1. Import a Sprite:
o Drag and drop an image (.png or .jpg) into the Assets folder in Unity.
o Select the image in the Inspector, set Texture Type to Sprite, and apply
changes.
2. Add the Sprite to the Scene:
o Drag the sprite from Assets into the Scene View or Hierarchy.
o Adjust its position using the Move Tool (W).
3. Modify the Sprite:
o Scale (R) – Resize the sprite.
o Rotate (E) – Rotate the sprite.
o Sorting Layer – Change the sprite's layer to determine rendering order (e.g.,
background vs. foreground).
2. Adding UI Elements
Unity’s UI system is used for game menus, score displays, health bars, etc.
1. Create a UI Canvas:
o Go to GameObject → UI → Canvas (if it doesn’t exist).
o Set Render Mode to Screen Space - Overlay.
2. Add UI Elements:
o Add text (TextMeshPro recommended) for scores and labels.
o Add buttons, images, sliders, or progress bars.
3. Position UI Elements:
o UI elements are positioned using Rect Transform instead of regular
Transform.
o Adjust Anchors to make the UI responsive.
3. Adding Tilemaps (for Level Design)
Unity’s Tilemap system is used to create 2D game levels efficiently.
1. Create a Tilemap:
o Go to GameObject → 2D Object → Tilemap → Rectangular.
o A Grid and Tilemap will appear in the Hierarchy.
2. Import and Set Up Tiles:
o Drag a tile sprite into Assets.
o Open Tile Palette (Window → 2D → Tile Palette).
o Create a new palette and drag the sprite into it.
3. Paint Tiles into the Scene:
o Select the Tilemap in the Hierarchy.
o Use the Paint Tool (B) to draw tiles.
Adding a Rigidbody2D:
Adding a Collider2D:
1. Create a Prefab:
o Drag an object (e.g., a player sprite with scripts and colliders) from the
Hierarchy into the Assets folder.
o This creates a Prefab.
2. Instantiate a Prefab in the Scene:
o Drag the prefab into the Scene View.
o It retains its properties (colliders, scripts, animations).
3. Instantiate Prefabs via Script:
void Start() {
Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
}
using UnityEngine;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * speed, rb.velocity.y);
}
}
Attach this script to the player GameObject.
Allows left/right movement with Arrow Keys / A & D.
Conclusion
Adding objects in Unity 2D involves placing sprites, UI elements, Tilemaps, physics
objects, and prefabs into a scene. By organizing objects properly, adding physics
interactions, UI, scripts, and prefabs, you can build a functional and visually appealing 2D
game world.
1. Create a Prefab:
o Drag a GameObject (e.g., a sprite with a Rigidbody2D) from the Hierarchy
into the Assets folder.
o This creates a Prefab that can be instantiated.
2. Create a Script to Spawn Objects Automatically
using UnityEngine;
void Start() {
InvokeRepeating("SpawnObject", 1f, spawnInterval);
}
void SpawnObject() {
Vector2 spawnPosition = new Vector2(Random.Range(-5f, 5f), 5f); // Random X, fixed Y
Instantiate(objectPrefab, spawnPosition, Quaternion.identity);
}
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity);
}
}
}
using UnityEngine;
void Start() {
for (int x = 0; x < cols; x++) {
for (int y = 0; y < rows; y++) {
Vector2 position = new Vector2(x * spacing, y * spacing);
Instantiate(tilePrefab, position, Quaternion.identity);
}
}
}
}
using UnityEngine;
void Update() {
if (Time.time > nextSpawn) {
nextSpawn = Time.time + spawnRate;
Vector2 spawnPosition = new Vector2(player.position.x + 10, Random.Range(-2f, 2f));
Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
}
}
}
using UnityEngine;
using System.Collections.Generic;
void Start() {
bulletPool = new List<GameObject>();
for (int i = 0; i < poolSize; i++) {
GameObject obj = Instantiate(bulletPrefab);
obj.SetActive(false);
bulletPool.Add(obj);
}
}
public GameObject GetPooledObject() {
foreach (GameObject obj in bulletPool) {
if (!obj.activeInHierarchy) {
return obj;
}
}
return null; // No inactive objects available
}
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
GameObject bullet = objectPool.GetPooledObject();
if (bullet != null) {
bullet.transform.position = transform.position;
bullet.SetActive(true);
}
}
}
}
using UnityEngine;
void Start() {
for (int i = 0; i < terrainLength; i++) {
float height = Random.Range(0f, 3f);
Vector2 position = new Vector2(i, height);
Instantiate(terrainBlock, position, Quaternion.identity);
}
}
}
void Start() {
Destroy(gameObject, lifetime);
}
}
Conclusion
Automatic object creation in Unity 2D is essential for spawning enemies, bullets, power-
ups, and procedural levels. Techniques like Instantiate(), Object Pooling, and Procedural
Generation help create dynamic and optimized game environments. 🚀
Drag the Prefab from Assets into the Scene multiple times.
using UnityEngine;
public class ObjectSpawner : MonoBehaviour {
public GameObject prefab; // Assign in Inspector
public float spawnTime = 2f;
void Start() {
InvokeRepeating("SpawnPrefab", 1f, spawnTime);
}
void SpawnPrefab() {
Vector2 spawnPosition = new Vector2(Random.Range(-5f, 5f), 5f);
Instantiate(prefab, spawnPosition, Quaternion.identity);
}
}
Prefab Variants
Prefab Variants allow creating different versions of a Prefab while still inheriting
properties from the original.
Example: A basic enemy prefab can have variants for different difficulty levels.
Conclusion
Prefabs in Unity 2D are essential for efficient game development, allowing reusable objects
with predefined properties. They can be instantiated dynamically, modified without
affecting the original, and extended using Prefab Variants. 🎮
Lighting in Unity 2D
Lighting in Unity 2D enhances the visual aesthetics, depth, and atmosphere of a game.
Unity provides a 2D lighting system that allows developers to create dynamic, realistic, and
stylized lighting effects using the Universal Render Pipeline (URP).
Conclusion
Lighting in Unity 2D plays a crucial role in setting the mood, depth, and realism of a game.
By using 2D Lights, URP, Shadows, and Post-Processing, you can create dynamic and
immersive game environments. 🚀🎮
RGB (Red, Green, Blue) color space in Unity 2D defines how colors are represented,
processed, and displayed in the game. Unity primarily works with RGB color models, where
each color is a combination of Red, Green, and Blue values ranging from 0 to 255 (8-bit) or
0.0 to 1.0 (float values).
Color myColor = new Color(1.0f, 0.5f, 0.0f, 1.0f); // Orange (R=1, G=0.5, B=0, A=1)
void Start() {
spriteRenderer.color = new Color(1f, 0f, 0f, 1f); // Set color to red
}
void Start() {
spriteRenderer.color = new Color(1f, 0f, 0f, 1f); // Set color to red
}
b) Changing UI Colors
void Start() {
uiElement.color = new Color(0f, 0.5f, 1f, 1f); // Set color to light blue
}
Color myColor;
ColorUtility.TryParseHtmlString("#FF5733", out myColor);
spriteRenderer.color = myColor;
Example:
Color hdrColor = new Color(2f, 0.5f, 0.5f, 1f); // Overbright red for HDR effect
Conclusion
RGB color space in Unity 2D defines how colors are displayed and processed in games.
Unity provides multiple color handling options, including RGB values, Hex codes, HDR
colors, and Linear/Gamma spaces. Understanding these options helps create visually
appealing 2D games with accurate color representation. 🎨🚀
Transparency in Unity 2D
Transparency in Unity 2D allows objects to be semi-transparent, fully transparent, or
have smooth fade effects. Transparency is mainly controlled using Alpha (A) values in
Unity’s Color system and Materials/Shaders.
void Start() {
Color color = spriteRenderer.color;
color.a = 0.5f; // 50% transparency
spriteRenderer.color = color;
}
void Start() {
Color color = uiElement.color;
color.a = 0.3f; // 30% transparency
uiElement.color = color;
}
Works for buttons, panels, images, or text.
Steps:
void Start() {
Color color = material.color;
color.a = 0.2f; // 20% opacity
material.color = color;
}
void Start() {
StartCoroutine(FadeOut());
}
IEnumerator FadeOut() {
for (float alpha = 1f; alpha >= 0; alpha -= 0.1f) {
Color color = spriteRenderer.color;
color.a = alpha;
spriteRenderer.color = color;
yield return new WaitForSeconds(0.1f);
}
}
IEnumerator FadeIn() {
for (float alpha = 0f; alpha <= 1; alpha += 0.1f) {
Color color = spriteRenderer.color;
color.a = alpha;
spriteRenderer.color = color;
yield return new WaitForSeconds(0.1f);
}
}
1. Import a Texture:
o Drag a .PNG or .JPG into the Assets folder.
o In the Inspector, set:
Texture Type: Sprite (2D and UI).
Filter Mode: Point (for pixel art) or Bilinear/Trilinear
(for smooth textures).
Compression: None (for best quality).
2. Create a Sprite GameObject:
o Go to GameObject → 2D Object → Sprite.
o Assign the imported texture to the SpriteRenderer in the Inspector.
void Start() {
spriteRenderer.material = customMaterial;
}
void Update() {
spriteRenderer.material.mainTextureOffset += new Vector2(Time.deltaTime * 0.5f, 0);
}
Conclusion
Texture mapping in Unity 2D involves applying textures to sprites, UI elements, and
Tilemaps. Using materials, shaders, and texture properties like scaling, tiling, and
offsetting, you can create visually rich 2D games with dynamic effects like scrolling,
blending, and animation. 🚀🎮
Collectibles in Unity 2D
Collectibles in Unity 2D are objects that a player can pick up, such as coins, keys, power-
ups, or health items. These items often increase score, health, or unlock new abilities.
using UnityEngine;
using UnityEngine;
using UnityEngine.UI;
void Awake() {
instance = this; // Singleton pattern
}
public void AddScore(int amount) {
score += amount;
scoreText.text = "Score: " + score;
}
}
using UnityEngine;
void Start() {
for (int i = 0; i < collectibleCount; i++) {
Vector2 spawnPos = new Vector2(Random.Range(-5f, 5f), Random.Range(-3f, 3f));
Instantiate(collectiblePrefab, spawnPos, Quaternion.identity);
}
}
}
Floating Effect
void Update() {
transform.position = new Vector2(transform.position.x, Mathf.Sin(Time.time) * 0.2f +
transform.position.y);
}
Makes the collectible move up and down.
Rotating Effect
void Update() {
transform.Rotate(new Vector3(0, 0, 100) * Time.deltaTime);
}
void Start() {
audioSource = GetComponent<AudioSource>();
}
Steps:
using UnityEngine;
void Update() {
if (waypoints.Length == 0) return;
transform.position = Vector2.MoveTowards(
transform.position,
waypoints[currentWaypointIndex].position,
speed * Time.deltaTime
);
using Pathfinding;
using UnityEngine;
void Start() {
seeker = GetComponent<Seeker>();
InvokeRepeating("UpdatePath", 0f, 0.5f);
}
void UpdatePath() {
if (seeker.IsDone())
seeker.StartPath(transform.position, target.position, OnPathComplete);
}
void OnPathComplete(Path p) {
if (!p.error) path = p;
}
void Update() {
if (path == null || currentWaypoint >= path.vectorPath.Count) return;
transform.position = Vector2.MoveTowards(
transform.position,
path.vectorPath[currentWaypoint],
speed * Time.deltaTime
);
using UnityEngine;
using UnityEngine.AI;
void Start() {
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false; // Important for 2D
agent.SetDestination(target.position);
}
void Update() {
agent.SetDestination(target.position);
}
}
using UnityEngine;
public class SimpleAI : MonoBehaviour {
public float speed = 2f;
public float detectionDistance = 1f;
void Update() {
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, detectionDistance);
if (hit.collider != null) {
transform.Rotate(0, 0, 90); // Turn if obstacle detected
} else {
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
}
}
Conclusion
Pathfinding in Unity 2D depends on the game’s needs:
using UnityEngine;
void Start() {
cam = Camera.main.transform;
lastCamPosition = cam.position;
}
void Update() {
Vector3 delta = cam.position - lastCamPosition;
transform.position += new Vector3(delta.x * speed, delta.y * speed, 0);
lastCamPosition = cam.position;
}
}
Adding 2D Lights
1. GameObject → Light → 2D Global Light (for overall brightness).
2. GameObject → Light → 2D Point Light (for lamps, torches).
3. Adjust Color, Intensity, and Shadows.
using UnityEngine;
Conclusion
Creating a 2D environment in Unity involves Tilemaps, Sprites, Lighting, and Physics.
By using Parallax effects, interactive objects, and optimized colliders, you can design
immersive, high-performance 2D game worlds! 🎮🚀