Attaching a script to an instances scene via code

Godot Version

4.2.1

Question

is it possible to do that? for context, im making a street fighters style game and i have a big roster. I have 2 scripts, one for player 1 and one for player 2. they are exactly the same, in exception of the controls (one is K&M and the other one is controller). i want to be able to instance one of my scenes in the character selection menu, say for example, character1, and add player1 script. then select character2 and add player2 script. Having the scripts already in the scenes is not an option, since first of all there are more characters, and second, player1 could choose character2 and viceversa and it would break everything

You can attach a script with set_script method: node.set_script(load("your_script_path"))

However, having two nearly identical scripts seems like a bad idea because you would always need to edit them both when making changes. Are your familiar with Input Map? You can find it from Project Settings. There you can define inputs for all input devices. For example, you could define an input action “jump” and then add input events that should trigger it (like “space” key for keyboard and mouse, “A” button for Xbox controller and so on). Then, in your code you can write Input.is_action_pressed("jump") and it works for both keyboard and controller.

2 Likes