Aller au contenu

How to detect when a variable changes and trigger actions

Ce contenu n’est pas encore disponible dans votre langue.

💡 Struggling with variable monitoring and event detection in Scratch? 🚀 Get Expert Help

CW

CodeWatcher_Dev

Posted on July 22, 2025 • Intermediate

🔍 Need help detecting variable changes

I’m working on a game where I need to trigger actions when a variable increases by 1. For example, when the score goes up, I want to play a sound effect or show an animation.

I tried something like this but it doesn’t work:

when green flag clicked
forever
if <(variable) goes up by (1)> then
Do this
end
end

Obviously “goes up by” isn’t a real block in Scratch! 😅

How can I detect when a variable changes and execute code only when it happens? I don’t want the code to run continuously - just once when the value actually changes.

VM

VariableMonitor_Pro

Replied 8 minutes later • ⭐ Best Answer

@CodeWatcher_Dev Great question! This is a common challenge in Scratch. The solution is to use a “shadow variable” to track the previous value and compare it with the current value.

🎯 Variable Change Detection System

Here’s how the detection system works:

flowchart TD A[🎮 Game Start] --> B[Initialize Variables] B --> C[Set shadow_var = main_var] C --> D[🔄 Main Loop] D --> E{main_var ≠ shadow_var?} E -->|No Change| F[Continue Loop] E -->|Changed!| G[🎉 Execute Action] G --> H[Update shadow_var] H --> I{What type of change?} I -->|Increased| J[🔺 Handle Increase] I -->|Decreased| K[🔻 Handle Decrease] I -->|Other| L[⚡ Handle General Change] J --> M[Update shadow_var = main_var] K --> M L --> M M --> F F --> D style A fill:#e1f5fe style G fill:#e8f5e8 style J fill:#fff3e0 style K fill:#fce4ec

📋 Step 1: Basic Change Detection

First, create a shadow variable to store the previous value:

    when flag clicked
// Initialize the shadow variable
set [score_shadow v] to (score)

// Main detection loop
forever
// Check if the main variable has changed
if <not <(score_shadow) = (score)>> then
// Variable changed! Execute your action here
play sound [ding v]

// Update shadow variable to current value
set [score_shadow v] to (score)
end
end
  

🔺 Step 2: Detecting Specific Changes (Increase/Decrease)

To detect if a variable specifically increased or decreased:

    when flag clicked
set [score_shadow v] to (score)

forever
if <not <(score_shadow) = (score)>> then
// Check if score increased
if <(score) > (score_shadow)> then
// Score went up!
set [change_amount v] to ((score) - (score_shadow))
say (join [Score increased by ] (change_amount)) for [1] seconds
play sound [level up v]

else
// Score went down
set [change_amount v] to ((score_shadow) - (score))
say (join [Score decreased by ] (change_amount)) for [1] seconds
play sound [lose life v]
end

// Always update shadow after handling the change
set [score_shadow v] to (score)
end
end
  

⚡ Step 3: Advanced Detection with Custom Blocks

For cleaner code, create custom blocks:

    // Custom block: Monitor variable changes
define monitor variable (variable_name) with shadow (shadow_name)
if <not <(variable_name) = (shadow_name)>> then
broadcast (join [variable_changed_] (variable_name))
set (shadow_name) to (variable_name)
end

// Usage in main script
when flag clicked
set [score_shadow v] to (score)
set [health_shadow v] to (health)
set [lives_shadow v] to (lives)

forever
monitor variable (score) with shadow (score_shadow)
monitor variable (health) with shadow (health_shadow)
monitor variable (lives) with shadow (lives_shadow)
end
  

🎮 Step 4: Handling Different Variable Events

Create specific handlers for different variables:

    // Handle score changes
when I receive [variable_changed_score v]
if <(score) > (score_shadow)> then
// Score increased
set [points_gained v] to ((score) - (score_shadow))

// Different effects based on points gained
if <(points_gained) >= [100]> then
broadcast [big_score_bonus v]
start sound [fanfare v]
else
start sound [coin v]
end

// Show floating text effect
create clone of [floating_text v]
end

// Handle health changes
when I receive [variable_changed_health v]
if <(health) < (health_shadow)> then
// Health decreased - player took damage
broadcast [player_hurt v]
set [brightness v] effect to [-50]
wait [0.1] seconds
set [brightness v] effect to [0]
else
// Health increased - player healed
broadcast [player_healed v]
set [color v] effect to [50]
wait [0.2] seconds
set [color v] effect to [0]
end
  

🔄 Step 5: Multiple Variable Monitoring

Monitor several variables efficiently:

    when flag clicked
// Initialize all shadow variables
set [score_shadow v] to (score)
set [health_shadow v] to (health)
set [ammo_shadow v] to (ammo)
set [level_shadow v] to (level)

forever
// Check score changes
if <not <(score) = (score_shadow)>> then
broadcast [score_changed v]
set [score_shadow v] to (score)
end

// Check health changes
if <not <(health) = (health_shadow)>> then
broadcast [health_changed v]
set [health_shadow v] to (health)
end

// Check ammo changes
if <not <(ammo) = (ammo_shadow)>> then
broadcast [ammo_changed v]
set [ammo_shadow v] to (ammo)
end

// Check level changes
if <not <(level) = (level_shadow)>> then
broadcast [level_changed v]
set [level_shadow v] to (level)
end
end
  

💡 Pro Tips

  • Performance: Only monitor variables that actually need change detection
  • Initialization: Always set shadow variables when the game starts
  • Broadcasts: Use broadcasts to keep your code organized and modular
  • Timing: The detection happens every frame, so actions trigger immediately

This technique is essential for creating responsive games with proper feedback systems! 🎮

CW

CodeWatcher_Dev

Replied 14 minutes later

@VariableMonitor_Pro This is exactly what I needed! 🎉

The shadow variable technique is brilliant - I never thought of storing the previous value to compare. I implemented the basic version and it works perfectly!

Now my score increases trigger sound effects and my health changes show visual feedback. Thank you so much! 🙏

GE

GameEngine_Expert

Replied 1 hour later

Excellent explanation! 👏 One additional tip: you can also use this technique to create “threshold events” - actions that trigger when a variable crosses specific values.

For example, trigger a “low health warning” when health drops below 20, or unlock achievements when score reaches certain milestones. Very useful for game progression systems!

VB

Vibelf_Community

Pinned Message • Moderator

🔍 Variable Monitoring & Event Systems

Great discussion on variable change detection! For advanced event-driven programming, our tutors can help you master:

  • ⚡ Complex event systems and state machines
  • 🎯 Performance optimization for multiple variable monitoring
  • 🔄 Advanced trigger conditions and thresholds
  • 📊 Data-driven game mechanics
  • 🎮 Professional game architecture patterns

📚 Related Topics

Ready to build sophisticated event-driven games? Get personalized guidance from our programming experts!