3. Prompt Engineering
c. Fixing a Bug

Fixing Bugs in AI-Generated Code

When SuperbulletAI generates code that doesn't work as expected, effective debugging and communication strategies can quickly get you back on track. Here's your systematic approach to fixing AI-generated bugs.


1. Using Console Output for Quick Fixes

Before you start debugging, you need to access the Output window where all errors and print statements appear:

  1. Open Roblox Studio
  2. Click View in the top menu bar
  3. Click Output (or find it in the list of windows)

Now you're ready to start debugging!

Copy-Paste Console Errors Method

One of the most effective debugging techniques is directly copying the Roblox Studio console output:

Step 1: Copy the exact console output

Here's the console output when the bug occurs:

ServerScriptService.MainScript:45: attempt to call method 'FireAllClients' of nil
Stack Begin
Script 'ServerScriptService.MainScript', Line 45 - function handlePlayerJoined
Script 'ServerScriptService.MainScript', Line 12
Stack End

Fix this error and explain what's wrong.

Step 2: Ask for explanation in natural language

Explain this error in simple English - what does 'attempt to call method
'FireAllClients' of nil' mean? Why is this happening and how does your fix
prevent it in the future?

Benefits of Console Copy-Paste

  • Immediate context - AI sees exact error location and stack trace
  • No interpretation errors - Exact error text prevents miscommunication
  • Stack trace analysis - AI can trace the problem through call hierarchy
  • Self-diagnosis capability - AI often identifies root cause immediately

Real Example

Console Output:

ReplicatedStorage.RemoteEvents.PlayerDamage is not a valid member of ReplicatedStorage "ReplicatedStorage"
Stack Begin
ServerScriptService.CombatSystem:23: function dealDamage
ServerScriptService.CombatSystem:8: function onHit
Stack End

Your Prompt:

Here's the error from Roblox Studio console:

ReplicatedStorage.RemoteEvents.PlayerDamage is not a valid member of ReplicatedStorage "ReplicatedStorage"
Stack Begin
ServerScriptService.CombatSystem:23: function dealDamage
ServerScriptService.CombatSystem:8: function onHit
Stack End

Fix this and explain in plain English what this error means and why it happened.

Expected AI Response Pattern:

  • Immediate fix (creating the missing RemoteEvent)
  • Plain English explanation ("The script is looking for a RemoteEvent called 'PlayerDamage' but it doesn't exist...")
  • Prevention advice ("Always create RemoteEvents before scripts try to use them...")

2. Add Debugging Prints with Unique Prefixes

The Simple Approach

Start with a simple, general request:

Add debugging prints with unique prefixes so we can properly identify the issue.

This lets the AI intelligently add prints at key points throughout your code. The AI will determine where logs are most useful.

When to Be Specific

Only specify exact sections/prefixes if you already know what's missing:

Prompt:

Add debugging prints with "[TELEPORT]" prefix specifically for:
- When player touches the pad
- When destination is calculated
- Right before the CFrame changes

I need to see if the destination calculation is the problem.

Expected Output:

local function onTeleportPadTouch(otherPart)
    print("[TELEPORT] Player detected:", otherPart.Parent.Name)
 
    local character = otherPart.Parent
    local humanoid = character:FindFirstChild("Humanoid")
 
    if humanoid then
        print("[TELEPORT] Character found:", character.Name, "at position:", character.HumanoidRootPart.Position)
 
        local destination = workspace.TeleportDestination
        print("[TELEPORT] Destination:", destination.Position)
 
        character.HumanoidRootPart.CFrame = destination.CFrame
        print("[TELEPORT] Success: Player teleported to", destination.Position)
    else
        print("[TELEPORT] ERROR: No humanoid found in", otherPart.Parent.Name)
    end
end

Copy-Paste Debug Logs to AI

When you have debug output, copy it directly to the AI:

Here are the debug logs from the console with the unique prefixes I added:

[TELEPORT] Player detected: Player1
[TELEPORT] Character found: Player1 at position: 10, 5, 20
[TELEPORT] Destination: 50, 5, 100
[TELEPORT] ERROR: No humanoid found in Player1

The logs show the character is found but then says no humanoid found.
This doesn't make sense. Fix this logic error.

When AI Gets Stuck - Adjust Log Depth

If the AI can't figure out the issue from current logs, adjust the logging level:

Go Deeper (More Detailed):

The issue is still not clear. Add much more detailed debugging prints that show:
- Every step inside the function
- All variable values at each step
- Every condition check and its result

Go deeper into the logic to find where it's failing.

Go Higher Level (Broader Context):

The detailed logs aren't helping. Add higher-level debugging that shows:
- Which systems are calling this function
- What state the game is in when this runs
- What happened before this function was called

Give me broader context to understand the bigger picture.

Example of Going Deeper:

The teleport is still failing but I don't know why. Add debugging prints inside
every if statement, every loop, and after every variable assignment in the
teleport function. I need to see the exact line where it breaks.

Example of Going Higher:

The error happens during teleport but I don't understand why it's being called
at the wrong time. Add higher-level logs showing what triggers the teleport
system and the game state before teleport is attempted.

Multi-Layer Debugging Strategy

If you need comprehensive debugging across multiple systems:

Fix this error, then add debugging prints with unique prefixes that show:
- When each function is called
- What values are passed between functions
- State of important variables at each step
- Any error conditions

This will help me understand the code flow and quickly identify issues.

Benefits of Unique Prefix Debugging

  • Easy filtering - Quickly find relevant logs in busy console output
  • Clear context - Immediately know which system/function is logging
  • Better AI analysis - AI can see exact execution flow and identify logic errors
  • Faster debugging - No need to guess which print statement triggered
  • Version tracking - Can see if code sections are being executed at all

3. Identify the Problem Precisely

Gather Essential Information

Before asking for a fix, collect these details:

What's broken:

  • Exact error messages (copy them word-for-word)
  • Which part of the functionality fails
  • When the issue occurs (on startup, during gameplay, specific actions)

What you expected:

  • Describe the intended behavior
  • Reference your original prompt if needed

Current behavior:

  • What actually happens instead
  • Any partial functionality that works

Example Problem Report

BAD: "The teleport script doesn't work"

GOOD: "The teleport script throws 'Workspace.TeleportPad.Script:12: attempt to index nil with 'Character'' when players step on the pad. I expected players to teleport to the spawn point, but instead they get an error and nothing happens."

4. Debugging Strategies by Error Type

Script Errors and Exceptions

For Roblox Script Errors:

Fix this error in the teleport script: 'Workspace.TeleportPad.Script:12:
attempt to index nil with 'Character''. The error occurs when any player
steps on the teleport pad. Add proper nil checking and error handling.

For Logic Errors:

The damage calculation is applying 50 damage instead of the intended 25.
The weapon stats show BaseDamage = 25, but players are taking double damage.
Check the damage formula and fix the multiplication error.

Performance Issues

For Lag/Stuttering:

The particle system causes severe lag when more than 3 players use magic spells
simultaneously. The game drops from 60fps to 15fps. Optimize the particle
generation to handle 10+ concurrent users without performance loss.

For Memory Leaks:

The zombie spawning system creates objects that never get cleaned up.
After 10 minutes of gameplay, there are 500+ zombie parts in workspace
causing memory issues. Add proper cleanup when zombies are destroyed.

Integration Problems

For System Conflicts:

The new inventory system conflicts with the existing shop system.
When players purchase items, they appear in the shop inventory but
not in the main inventory. Make both systems share the same data source.

5. Effective Bug Report Prompts

Template for Bug Reports

BUG FIX REQUEST:

Original feature: [Brief description of what was supposed to work]

Current problem: [Specific issue with exact error messages]

Expected behavior: [What should happen instead]

Context: [When/how the bug occurs]

Additional info: [Any relevant details about your game setup]

Please fix this issue and explain what was wrong.

Real Example

BUG FIX REQUEST:

Original feature: Player respawn system that teleports dead players to
random spawn points after 5 seconds

Current problem: Players respawn immediately at (0,0,0) instead of spawn
points. No 5-second delay occurs. Error in output: 'ReplicatedStorage.SpawnData
is not a valid member of ReplicatedStorage'

Expected behavior: 5-second countdown, then teleport to one of 8 designated
spawn points randomly

Context: Happens every time any player dies from fall damage or combat

Additional info: Using FilteringEnabled, spawn points are in workspace
folder called 'SpawnPoints'

Please fix this issue and explain what was wrong.

6. Providing Context for Complex Bugs

Include Relevant Code Snippets

When reporting bugs, include the problematic section:

This section of the generated code is causing the error:

local function teleportPlayer(player)
    local character = player.Character  -- This line fails
    character.HumanoidRootPart.CFrame = spawnPoint.CFrame
end

The error suggests 'player.Character' is nil. Fix this with proper validation.

Describe Your Game Environment

Additional context for the bug fix:
- Game uses R15 character rigs
- Custom character controller is active
- Players can join mid-game
- Using team-based spawning system

7. Incremental Debugging Approach

Start with Minimal Fixes

First: Address the immediate error

Fix the nil reference error in line 12 of the teleport script.
Just make it work without crashing.

Then: Improve functionality

Now add validation to ensure the teleport destination exists
before attempting to teleport.

Finally: Add polish

Add smooth teleport effects and sound feedback to the working
teleport system.

Test Each Fix Separately

Test this fix by having multiple players use the teleport simultaneously.
If any new errors occur, report them with the exact error messages.

8. Common Roblox Bug Patterns and Solutions

Character/Player Issues

Problem: player.Character is nil
Fix Request: "Add character validation before accessing character properties"

Problem: Humanoid not found
Fix Request: "Add Humanoid existence checking with proper wait logic"

Remote Events/Security Issues

Problem: Remote events not firing
Fix Request: "Debug the RemoteEvent connection and ensure client-server communication works"

Problem: Exploiter protection failing
Fix Request: "Add server-side validation for all RemoteEvent parameters"

Data Storage Problems

Problem: DataStore errors
Fix Request: "Add error handling for DataStore operations with retry logic"

Problem: Data not saving
Fix Request: "Debug the data saving process and add success/failure feedback"

9. Getting Educational Explanations

Ask "Why" Questions

Don't just ask for fixes - build your understanding:

Fix this error, then explain:
1. Why did this specific error occur?
2. What does 'attempt to index nil' actually mean?
3. How can I recognize this pattern in future code?
4. What are the warning signs I should watch for?

Request Learning-Focused Responses

Treat me like I'm learning Roblox scripting. Fix this error and explain
it step-by-step so I understand what went wrong and can avoid it next time.

Common Error Explanations to Request

Nil Reference Errors:

Explain what 'nil' means in this context and why the object doesn't exist
when the script expects it to.

Timing Issues:

Explain why this script runs before the object is created and how to
properly wait for objects in Roblox.

Scope Problems:

Explain why this variable isn't accessible here and how Roblox script
scope works.

10. Advanced Error Handling and Robustness

Request Comprehensive Error Handling

Add comprehensive error handling to this system:
- Try-catch blocks (pcall) for risky operations
- Graceful degradation when services fail
- User-friendly error messages instead of script errors
- Logging that helps trace problems
- Retry logic for temporary failures

Performance Monitoring

Add performance timing measurements to identify bottlenecks:
- Time each major operation
- Log when operations exceed expected duration
- Add warnings for performance issues

11. When to Ask for Complete Rewrites

Red Flags for Rewriting

  • Multiple interconnected bugs
  • Performance is fundamentally flawed
  • Security vulnerabilities throughout
  • Code structure makes fixes impossible

Rewrite Request Template

The current implementation has fundamental issues that can't be patched:
1. [List major problems]
2. [Performance concerns]
3. [Security issues]

Please rewrite this system from scratch with these requirements:
- [Specific requirements]
- [Performance targets]
- [Security considerations]

Keep the same external interface but redesign the internal logic.

12. Preventing Future Bugs

Specify Robustness Requirements

In your original prompts:

Create a robust teleport system that handles:
- Players leaving during teleport
- Invalid teleport destinations
- Network lag and disconnections
- Multiple simultaneous teleports

Request Testing Code

Also create a test script that verifies this system works correctly
under various conditions and edge cases.

Quick Reference: Bug Fix Prompt Template

FIX: [System name] - [Brief issue description]

Error: [Exact error message or unexpected behavior]

Expected: [What should happen]

When: [Specific conditions when bug occurs]

Fix needed: [Specific change requested]

Example:

FIX: Jump Pad System - Players not launching

Error: No upward velocity applied when stepping on pad,
no error messages in console

Expected: Players should launch 50 studs upward with trail effect

When: Happens with all players on all jump pads

Fix needed: Debug the velocity application and add visual feedback

Remember: Clear bug reports lead to quick fixes. The more specific you are about the problem, the faster SuperbulletAI can provide an effective solution.