Easier way to give nodes the same code but with automatic "Replace All"?

PaulScottiPaulScotti Posts: 2Member

I have a 3D chess board of sorts, and each tile is called "A1", "B2", "G4", etc. Here is the code I have for the A1 node (in a script called A1.gd). When a mouse hovers over the tile, the game shows an object hovering above the tile.

extends StaticBody

func _ready():
    connect("mouse_entered", self, "_on_A1_mouse_entered")
    connect("mouse_exited", self, "_on_A1_mouse_exited")
func _on_A1_mouse_entered():
    .get_node("/root/Main/Board/Hover").visible = 1
    .get_node("/root/Main/Board/Hover").translation = get_translation()
func _on_A1_mouse_exited():
    .get_node("/root/Main/Board/Hover").visible = 0

I want the same code for all the other tiles, but with "A1" in this code replaced with the respective name for each tile. Right now the only way I can think to do this is to create a separate script for every single tile and paste into each script the above code and do a Replace All (e.g., "A1" -> "B1") every time.

Is there a better way to do this? I am a beginner in using Godot so I appreciate any help/advice. Thanks.

Comments

  • TwistedTwiglegTwistedTwigleg Posts: 2,810Admin

    Welcome to the forums @PaulScotti!

    Looking at the code, the only place where A1 is used is internally for connecting the signals, if I understand correctly. You should be able to attach the same script to each of the tiles and it should work, since the name of the node doesn't seem to make a difference one way or another. That said, it may be confusing from a programmer point of view though, with the current names. I would perhaps change the script to the following:

    extends StaticBody
    
    func _ready():
        connect("mouse_entered", self, "_on_mouse_entered_tile")
        connect("mouse_exited", self, "_on_mouse_exited_tile")
    func _on_mouse_entered_tile():
         .get_node("/root/Main/Board/Hover").visible = true
         .get_node("/root/Main/Board/Hover").translation = get_translation()
    func _on_mouse_exited_tile():
        .get_node("/root/Main/Board/Hover").visible = false
    

    That way, the names don't necessarily point to a specific tile, but are descriptive enough that they are hopefully clear as to what they do. :smile:

  • PaulScottiPaulScotti Posts: 2Member

    Ah, I didn't realize that the script can be used without referring to the node name! Thanks so much! In reading more into the documentation I also realized that if I use inheritance then I don't have to copy and paste this code into every node's own script!

Leave a Comment

BoldItalicStrikethroughOrdered listUnordered list
Emoji
Image
Align leftAlign centerAlign rightToggle HTML viewToggle full pageToggle lights
Drop image/file