Phaser Hooks - With Global State
Basic example using Phaser Hooks for global state management that persists across scenes.
With Global State
Basic example using Phaser Hooks for global state management that persists across scenes. Global state allows you to share data between different scenes in your game.
Features
- đ Global State: Shared state across all scenes in your game
- đ State Persistence: State persists when switching between scenes
- đĄ Change Listeners: React to state changes with onChange callbacks
- ⥠Performance: Optimized state management for 60fps gameplay
Live Example
Loading game...
Usage Example
import { useGlobalState } from 'phaser-hooks';
class GameScene extends Phaser.Scene {
create() {
// Get global state with initial value
const [score, setScore] = useGlobalState('score', 0);
const [health, setHealth] = useGlobalState('health', 100);
// Update global state
setScore(score + 10);
setHealth(health - 5);
// Listen to state changes
const [playerName, setPlayerName] = useGlobalState('playerName', 'Player', (newValue) => {
console.log('Player name changed to:', newValue);
});
}
}
class MenuScene extends Phaser.Scene {
create() {
// Access the same global state from another scene
const [score] = useGlobalState('score', 0);
const [health] = useGlobalState('health', 100);
console.log('Current score:', score);
console.log('Current health:', health);
}
} State Management
Basic Usage
- âĸ
useGlobalState(key, initialValue)- Get/set global state - âĸ State persists across scene changes
- âĸ Multiple scenes can access the same state
- âĸ Type-safe with TypeScript support
Advanced Features
- âĸ
onChangecallbacks for state changes - âĸ Automatic re-rendering when state changes
- âĸ Memory efficient state management
- âĸ Easy debugging and state inspection