Ruby(RGSS3)路径寻路函数报错:形参不可为全局变量
Hey there, let's break down this syntax error you're hitting in your pathfinding function. The issue is exactly what the error message states: Ruby (and RGSS3, which builds on Ruby) doesn't allow global variables like $game_player to be used as formal parameters in a method definition.
Why This Happens
Formal parameters are placeholders for local variables that will hold the values passed to the method when it's called. Global variables in Ruby are prefixed with $, and the language's syntax rules prevent you from declaring a parameter with that prefix—Ruby interprets this as an invalid attempt to create a local variable named $game_player, which isn't allowed.
Two Simple Fixes
1. Rename the Parameter to a Regular Local Variable
Change the parameter name to a standard local variable (without the $ prefix), then pass $game_player as an argument when you call the method. This keeps your method flexible (you could even pass other game objects like NPCs later if needed):
# Updated method definition with a valid parameter name def find_path(startx, starty, destx, desty, player) # Use the `player` local variable inside the method player_current_x = player.x player_current_y = player.y # Your pathfinding logic here... end # Call the method, passing the global $game_player as the argument find_path(5, 5, 15, 15, $game_player)
2. Remove the Parameter and Use the Global Variable Directly
If your method will always need to reference the player (and you don't plan to reuse it for other objects), you can skip passing $game_player as a parameter entirely and just access it directly inside the method:
# Method definition without the player parameter def find_path(startx, starty, destx, desty) # Access the global $game_player directly player_current_x = $game_player.x player_current_y = $game_player.y # Your pathfinding logic here... end # Call the method without passing the player argument find_path(5, 5, 15, 15)
Quick Tip
If you want to keep your code loosely coupled (a good practice for maintainability), go with the first option. Passing the player as an argument makes the method independent of the global variable, which makes testing and reusing the code easier down the line.
内容的提问来源于stack exchange,提问作者toto8080

