GameDesign Flashcards

1
Q

Explain how Unity’s MonoBehaviour class provides tight integration with the Game
Loop. Refer to appropriate methods of the MonoBehaviour class in your answer.

A
  • Integrates into the unity engine through lifecycle methods
    -Key Methods:
    Start(); Called once before the first frame. Used for initialization.
    Update(); Called every frame. Handles continuous logic (e.g., player input).
    FixedUpdate(); Called at fixed intervals. Used for physics calculations.
    OnEnable(); Triggered when a script or object is enabled.
    Event and timeloop driven methods
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a Coroutine in Unity, and how do Coroutines integrate with the Game Loop?

A

In Unity, a Coroutine is a special function that allows you to pause execution and resume it after a specified time, or even across multiple frames. Coroutines are extremely useful for implementing behaviors that take place over time without blocking the main game loop, such as animations, waiting for events, or timed sequences.oroutines are integrated into Unity’s Game Loop by being processed alongside the standard Update() method.
When you call StartCoroutine(), Unity registers the coroutine and starts executing it concurrently with the rest of your game’s logic.
Coroutines do not run on separate threads; instead, they are controlled by the Unity engine, which checks each frame if a coroutine should resume based on its yield condition.Non-blocking Execution: Coroutines allow you to perform time-consuming operations without freezing the game.
Simple Timing Control: They are ideal for creating timed events, delays, and sequences.
Flexible Control: Coroutines can be started, stopped, and interrupted easily using StartCoroutine(), StopCoroutine(), and StopAllCoroutines().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a collider

A
  1. Collider
    A Collider is a component in Unity that defines the shape of an object for the purpose of physical collisions. Colliders don’t need to be visible; they are used by the physics engine to detect when objects come into contact with one another.

Example Use:
A Box Collider on a wall ensures that a player cannot walk through it. If the player tries to move through the wall, the physics engine detects the collision and prevents further movement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a Trigger

A

Trigger
A Trigger is a special type of collider that does not block physical movement but instead detects when objects enter, exit, or stay within its boundaries. It is used for event-based interactions.

Example Use:
A Trigger can be used to detect when a player enters a certain area, such as a checkpoint in a game. When the player enters the trigger zone, it can save the game state or activate a cutscene.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Rigidbody

A

A Rigidbody is a component that enables an object to be affected by Unity’s physics engine, allowing it to respond to forces like gravity, collisions, and other physical interactions. By adding a Rigidbody to a game object, you make it behave like a real-world physical object.

Example Use:
A Rigidbody can be applied to a ball so that it can roll down a hill, bounce, and interact realistically with other physical objects in the game.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When is OnCollisionEnter Executed?

A

When is OnCollisionEnter Executed?
The OnCollisionEnter method in Unity is called when:

Two objects with Colliders come into contact with each other.
At least one of the objects has a Rigidbody component attached to it.
Both objects are not marked as “Trigger” (i.e., they are physical colliders, not triggers).
In other words, OnCollisionEnter is executed when there is a physical collision between two objects, where at least one of them is capable of being influenced by physics (i.e., it has a Rigidbody).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain in general terms (no precise code required)
how you could make use of the Collision.contacts argument received by
OnCollisionEnter, to instantiate ‘metallic spark’ special effect prefabs at the points of
contact, and have them correctly aligned so that the sparks move outwards from the
surface of contact.

A

How to Use Collision.contacts to Instantiate Effects
When OnCollisionEnter is triggered, it receives a Collision object as an argument. This Collision object contains information about the collision, including the contact points where the objects touched. You can use the Collision.contacts array to determine where and how to instantiate special effects, like “metallic sparks”.

General Approach to Instantiate ‘Metallic Sparks’
Iterate through the Contact Points:

The Collision.contacts array contains multiple contact points if the collision involves a complex surface. Each contact point includes information such as the position and normal of the contact.
Instantiate the Sparks at Each Contact Point:

Use the ContactPoint.point property to get the exact position of the contact on the surface.
Use the ContactPoint.normal property to determine the direction perpendicular to the surface at the point of contact. This normal can be used to align the spark effects so they appear to “shoot” out from the surface.
Align the Sparks:

To align the sparks correctly, use the normal vector to set the orientation of the instantiated spark prefab. This ensures that the sparks move outward from the surface of the collision.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Making appropriate use of local and global co-ordinates, write Unity3D/C# code
to perform the following transformations. You may assume that references to the
runtime game objects are provided:
* rotate a game object 5 degrees around the world’s y axis
* move a game object 7 units directly towards another game object
* move a game object 10 units forward in whatever direction it is facing

A

// Rotate the game object 5 degrees around the world’s Y axis
transform.Rotate(Vector3.up, 5.0f, Space.World);
//move a game object 7 units directly towards another game object
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, 7.0f);

//move a game object 10 units forward in whatever direction it is facing
transform.Translate(Vector3.forward * 10.0f, Space.Self);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write a single Unity (MonoBehaviour) C# script which is suitable for attaching to
any game object that you wish to orbit around another game object. The script should
offer inspector settings (i.e. public variables and object references) for defining the
object being rotated around, as well as the axis of rotation and the speed of rotation.

A

using UnityEngine;

public class OrbitingObject : MonoBehaviour
{
[Header(“Orbit Settings”)]
[Tooltip(“The object to orbit around”)]
public Transform target; // The object to orbit around

[Tooltip("Axis of rotation")]
public Vector3 orbitAxis = Vector3.up; // Axis of rotation (default is the Y axis)

[Tooltip("Speed of orbit in degrees per second")]
public float orbitSpeed = 10.0f; // Speed of orbit

[Tooltip("Distance from the target object")]
public float orbitDistance = 5.0f; // Initial distance from the target

private void Start()
{
    // Set the initial position based on the distance from the target
    if (target != null)
    {
        Vector3 direction = (transform.position - target.position).normalized;
        transform.position = target.position + direction * orbitDistance;
    }
}

private void Update()
{
    // Check if the target is assigned
    if (target != null)
    {
        // Rotate around the target object along the specified axis
        transform.RotateAround(target.position, orbitAxis.normalized, orbitSpeed * Time.deltaTime);
    }
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a Raycast in Unity?

A

What is a Raycast in Unity?
In Unity, raycasting is a technique used to detect objects in the scene by shooting an invisible “ray” from a specific point in a specific direction. The ray continues until it hits a collider, and it can be used to determine whether an object is present along that path.

Raycasts are extremely useful in games for:

Detecting whether a character is standing on the ground.
Checking line of sight between two objects.
Detecting obstacles in front of a moving object.
Interacting with objects via mouse clicks (like selecting or shooting).

How Raycasting Works
The ray is cast from a starting point in a specific direction.
If the ray hits an object with a collider, it returns information about that collision (e.g., the object hit, the distance, and the exact point of contact).
If no object is hit, the ray returns false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Code Simple raycasting

A

using UnityEngine;

public class GroundCheck : MonoBehaviour
{
void Update()
{
if (Physics.Raycast(transform.position, Vector3.down, out hit, 1.1f))
{
Debug.Log(“Standing on something at position: “);
}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

In the two-dimensional game depicted below, the game characters have
Rigidbody2D and Collider2D components, are moved left and right using the left/right
arrow keys, and can jump upwards when the up arrow key is pressed – but only if they
are standing on something. Their movement is controlled by the physics engine. Write
suitable Unity3D/C# code to implement these movement behaviours for a character,
indicating which methods the code is written in.

A

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
public float jumpForce = 10f;
public float rayLength = 0.6f; // Length of the ray for ground detection
private Rigidbody2D rb;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    // Move left and right using arrow keys
    float move = Input.GetAxis("Horizontal");
    rb.velocity = new Vector2(move * speed, rb.velocity.y);

    // Check if the character is on the ground using a raycast
    bool isGrounded = Physics2D.Raycast(transform.position, Vector2.down, rayLength);

    // Jump if the up arrow is pressed and the character is on the ground
    if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }
}

// Draw the ray in the Scene view for debugging
void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawLine(transform.position, transform.position + Vector3.down * rayLength);
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the Use of State Machines to Structure Game Logic

A

State Machines are a fundamental tool in game development for managing different states an entity or system can be in. For instance, a character can have states like “Idle”, “Walking”, “Jumping”, or “Attacking”. Each state encapsulates specific behaviors and transitions, ensuring that the character behaves correctly based on its current state. State Machines help to keep code organized, making it easier to manage complex logic without resorting to large if-else or switch statements. In Unity, state machines can be implemented using enums, switch statements, or more advanced techniques like ScriptableObject-based state patterns. They are also commonly used with Unity’s Animator Controller, where animations transition between states based on defined conditions. State Machines improve code maintainability, readability, and scalability, making them especially useful for AI behaviors, player controls, and game state management.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are Screen Space, Viewport Space, and World Space in Unity

A

n Unity, Screen Space, Viewport Space, and World Space are different coordinate systems used to position objects. Screen Space refers to pixel coordinates on the display (e.g., (0,0) is the bottom-left corner). Viewport Space normalizes coordinates between (0,0) and (1,1) based on the screen dimensions, making it independent of the device’s resolution. World Space represents the actual positions in the 3D game world using Unity’s coordinate system. To transform between these spaces, Unity provides methods like Camera.ScreenToWorldPoint() to convert screen coordinates to world coordinates and Camera.WorldToViewportPoint() for world-to-viewport conversions. These transformations are essential for placing UI elements, handling mouse clicks, and aligning objects relative to the screen or world space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the Object Pool Pattern – Why It’s Useful and How It Operates

A

The Object Pool Pattern is a performance optimization technique used to efficiently manage the creation and destruction of objects. In Unity, constantly instantiating and destroying objects (like bullets, enemies, or particles) can lead to significant performance overhead due to memory allocation and garbage collection. Instead, an Object Pool pre-creates a set of reusable objects and keeps them inactive until needed. When an object is required, the pool activates it, and when it’s no longer needed, it’s deactivated rather than destroyed. This reduces CPU usage and increases frame rates, especially in resource-intensive games. Unity developers commonly use object pools for frequently used objects that have short lifespans. Implementing object pools involves storing inactive objects in a list and reusing them when required, thus minimizing memory fragmentation and improving runtime efficiency.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are coroutines in Unity, Including Two Different Situations for Which Coroutines Would Be Useful

A

Coroutines in Unity are a powerful feature that allows functions to be paused and resumed over multiple frames without blocking the game’s main thread. This makes them ideal for handling time-based actions like animations, delays, or sequential events. Coroutines are implemented using IEnumerator and the yield keyword. For instance, they can be used to create smooth transitions by gradually changing values over time (e.g., fading in a UI element) or waiting for a few seconds before spawning enemies. Coroutines are also useful for implementing non-blocking loops, such as continuously checking for a condition without freezing the game. By using yield return new WaitForSeconds(), coroutines provide an easy way to delay actions without affecting game performance, making them a versatile tool for asynchronous tasks in Unity.

17
Q

Explain how you would display (and update) a score on the screen while a game is being
played, using the Unity GUI system.

A

Setting Up the UI:

First, create a Canvas in your Unity scene. This is necessary to render any UI elements on the screen.
Inside the Canvas, add a Text element from the UI menu. This Text component will display the score.
Customizing the Text:

Adjust the properties of the Text component, such as its font, size, and color, to match your game’s aesthetic.
Position the Text element on the screen where you want the score to appear (e.g., the top-left corner).
Updating the Score Programmatically:

To update the score during gameplay, create a C# script that holds a reference to the Text component.
In the script, use the text property of the Text component to change the displayed score whenever the player earns points.
Linking the Script to the Text Component:

Attach the script to a GameObject (such as an empty GameObject named “ScoreManager”).
Drag the Text component from the Canvas into the script’s public field in the Inspector.
During Gameplay:

The script will continuously update the Text component to reflect the current score. For instance, when the player collects an item or defeats an enemy, the score will increase, and the Text component will display the new score in real time.

18
Q

Explain garbage collection in Unity, including how to write low-garbage code.

A

In Unity, Garbage Collection (GC) is the process by which the system automatically reclaims memory that is no longer in use. It is necessary to free up memory that was allocated for objects that are no longer needed. However, garbage collection can cause performance hiccups because it temporarily pauses the game while it runs, leading to noticeable frame rate drops, especially in fast-paced games.

How Garbage Collection Works:
Unity uses a managed memory system, where objects are allocated on the heap.
When objects are no longer referenced, they become eligible for garbage collection.
The garbage collector periodically scans the memory for unused objects and reclaims that memory.
This process can result in performance spikes (frame drops) if it runs frequently, especially if large amounts of memory were allocated.
Tips for Writing Low-Garbage Code:
To minimize the impact of garbage collection in Unity, developers can adopt practices that reduce memory allocations:

Avoid Frequent Object Instantiation/Destruction:

Instead of creating and destroying objects repeatedly, use object pooling. For example, reusing bullets or enemies instead of creating new ones each time can significantly reduce garbage.
Minimize String Allocations:

Concatenating strings (“Score: “ + score) creates new strings in memory. Use StringBuilder or cache frequently used strings to avoid creating garbage.
Avoid Allocating Memory in Update():

Do not allocate new objects or arrays inside Update() or other frequently called methods. These will quickly fill up memory and trigger garbage collection.
Example: Instead of creating a new list every frame, reuse a pre-allocated list.
Use structs Instead of classes Where Possible:

structs are value types and are allocated on the stack, which is not managed by the garbage collector, reducing heap allocations.
Cache Component Lookups:

Calling GetComponent<T>() frequently allocates memory. Cache the reference in a variable if it's needed multiple times.</T>