Game Development with C# (Optional) - Textnotes

Game Development with C# (Optional)


C# is widely used in game development with Unity, a popular game engine that allows building 2D and 3D games for multiple platforms.

1. Unity with C#

  1. Unity uses C# scripts for game logic.
  2. Projects include:
  3. Assets → Scripts, sprites, models, sounds
  4. Scenes → Game levels or screens
  5. GameObjects → Everything visible or interactive in the game

Setup:

  1. Download Unity Hub → Install latest Unity Editor.
  2. Create a 3D or 2D project → Start scripting in C#.

2. Scripts & Components

  1. Scripts are C# classes derived from MonoBehaviour.
  2. Components define behaviors for GameObjects.

Example: Simple Player Movement


using UnityEngine;

public class PlayerController : MonoBehaviour
{
public float speed = 5f;

void Update()
{
float moveX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
float moveZ = Input.GetAxis("Vertical") * speed * Time.deltaTime;

transform.Translate(moveX, 0, moveZ);
}
}
  1. Attach script to a Player GameObject to control movement.

3. Game Objects

  1. GameObjects are everything in the scene: characters, cameras, lights, props.
  2. Components add functionality (e.g., Rigidbody for physics, Collider for collision).

// Access another GameObject
public GameObject enemy;

void Start()
{
enemy.SetActive(false); // Hide enemy at start
}

4. Animations

  1. Unity supports 2D and 3D animations.
  2. Use Animator component and Animation Clips.

Example: Triggering animation


Animator animator;

void Start()
{
animator = GetComponent<Animator>();
}

void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("Jump");
}
}
  1. Set triggers or bools in the Animator window to control animation states.

5. Event Handling in Games

  1. Handle input events, collisions, and triggers.

Collision Example


void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
Debug.Log("Hit by enemy!");
}
}

Trigger Example


void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Coin"))
{
Debug.Log("Coin collected!");
Destroy(other.gameObject);
}
}

Input Example


void Update()
{
if (Input.GetMouseButtonDown(0)) // Left click
{
Debug.Log("Mouse clicked");
}
}

Summary of Chapter 17:

  1. Unity + C#: Powerful combination for game development.
  2. Scripts & Components: Control GameObject behavior with C# scripts.
  3. Game Objects: Everything in the scene is a GameObject with components.
  4. Animations: Control animations via Animator component and triggers.
  5. Event Handling: Respond to input, collisions, and triggers in real-time.