01_Event-Driven Programming
Event-driven programming is a programming paradigm where the program reacts to events, such as user actions, sensor inputs, or system-generated signals. Instead of following a strict sequence of commands, the program listens for events and responds when they occur.
Core Concepts
1. Events
- Actions or occurrences that the program can respond to.
- Examples: Button clicks, keyboard input, mouse movement.
2. Event Handlers
- Functions or methods that execute in response to events.
3. Event Loop
- A continuous loop that listens for events and triggers their respective handlers when events occur.
Key Components
1. Basic Event-Driven Program
This example demonstrates a simple event-driven system with custom events and handlers.
# Simple Event-Driven Example
class Event:
def __init__(self, name):
self.name = name
# Event handlers
def handle_event_1(event):
print(f"Handling event: {event.name}")
def handle_event_2(event):
print(f"Handling another event: {event.name}")
# Main event loop
def event_loop(events):
for event in events:
if event.name == "event_1":
handle_event_1(event)
elif event.name == "event_2":
handle_event_2(event)
# Example usage
events = [Event("event_1"), Event("event_2"), Event("event_1")]
event_loop(events)
Output:
Handling event: event_1
Handling another event: event_2
Handling event: event_1
2. Keyboard Input Event Handling
Using Python's built-in keyboard
library to respond to keypresses.
import keyboard # Install with: pip install keyboard
def on_key_event(event):
print(f"Key {event.name} pressed!")
# Attach the event handler
keyboard.on_press(on_key_event)
# Keep the program running to listen for events
print("Press any key (Ctrl+C to exit)")
keyboard.wait() # Blocks and listens for events
What Happens:
- Whenever a key is pressed, the
on_key_event
function is executed.
3. Timer-Based Event Handling
This example uses the threading
library to trigger events based on a timer.
import threading
# Event handler
def on_timer_event():
print("Timer event triggered!")
# Set up a repeating timer
def start_timer():
threading.Timer(2.0, start_timer).start() # Triggers every 2 seconds
on_timer_event()
start_timer()
What Happens:
- The program triggers
on_timer_event
every 2 seconds.
4. Event Handling with PyQt
PyQt is another popular library for GUI development. It relies on signals and slots for event handling.
from PyQt5.QtWidgets import QApplication, QPushButton, QLabel, QVBoxLayout, QWidget
def on_button_click():
label.setText("Button clicked!")
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
label = QLabel("Click the button!")
button = QPushButton("Click Me")
button.clicked.connect(on_button_click) # Connect signal to handler
layout.addWidget(label)
layout.addWidget(button)
window.setLayout(layout)
window.show()
app.exec_()
What Happens:
5. AR Foundation Plane Detection Event
For AR Foundation, use ARPlaneManager
to detect planes in an AR session.
using UnityEngine;
using UnityEngine.XR.ARFoundation;
public class ARPlaneDetection : MonoBehaviour
{
[SerializeField] private ARPlaneManager planeManager;
void OnEnable()
{
planeManager.planesChanged += OnPlanesChanged;
}
void OnDisable()
{
planeManager.planesChanged -= OnPlanesChanged;
}
private void OnPlanesChanged(ARPlanesChangedEventArgs args)
{
foreach (var plane in args.added)
{
Debug.Log($"Plane added: {plane.trackableId}");
}
}
}
ExplanationWhat Happens:
- Event: Plane detection event in AR Foundation.
- Handler:
OnPlanesChanged
is executed whenever a plane is added, updated, or removed.
Best Practices for Event-Driven Programming in Unity
-
Use Built-in Events Where Possible:
- Leverage Unity's
UnityEvent
, UI events, and physics events instead of reinventing the wheel.
- Leverage Unity's
-
Avoid Overusing Global Events:
- Delegate-based or static events are powerful but can lead to tight coupling and difficulty debugging.
-
Unsubscribe When Done:
- Always unsubscribe from events to avoid memory leaks or unintended behavior.