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#
- Unity uses C# scripts for game logic.
- Projects include:
- Assets → Scripts, sprites, models, sounds
- Scenes → Game levels or screens
- GameObjects → Everything visible or interactive in the game
Setup:
- Download Unity Hub → Install latest Unity Editor.
- Create a 3D or 2D project → Start scripting in C#.
2. Scripts & Components
- Scripts are C# classes derived from
MonoBehaviour. - 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);
}
}
- Attach script to a Player GameObject to control movement.
3. Game Objects
- GameObjects are everything in the scene: characters, cameras, lights, props.
- 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
- Unity supports 2D and 3D animations.
- 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");
}
}
- Set triggers or bools in the Animator window to control animation states.
5. Event Handling in Games
- 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:
- Unity + C#: Powerful combination for game development.
- Scripts & Components: Control GameObject behavior with C# scripts.
- Game Objects: Everything in the scene is a GameObject with components.
- Animations: Control animations via Animator component and triggers.
- Event Handling: Respond to input, collisions, and triggers in real-time.