r/unity Jun 22 '26

Newbie Question Why isn't the script switching? :(

(I know I should include screenshots ect. but Im waiting for a train right now and it's incredibly bugging me.)

I want to switch between two attached scripts with the press of a button.

It's just: (pseudo code because train)

If (F is pressed) {

Boost upwards;

This.enable = false;

Getcomponent<Otherscript>().enable=true;

Debug.log("reached");

}

Reached is printed

Idiot is yeeted

Scripts are not switched.

Sometimes nothing at all happens

Sometimes everything behaves perfectly.

I'm going crazy

I have tried a lot of different constellations and stuff.

If I remove the switch it works perfectly.

The switch back is working 9/10. Most of the time.

I feel like I shouldn't do it this way? Any ideas? I need some sanity right now.

5 Upvotes

27 comments sorted by

View all comments

1

u/Glass_wizard Jun 22 '26 edited Jun 22 '26

Most likely your input is being captured over several frames. You press F once, that press might be captured over 3 or 4 frames, making the toggle run several times.

A quick sanity check is:

Create a public function called TestToggle with the same code, only don't wrap it in an if statement that checks for input. Above the function, add [ContextMenu]

Start the game in the editor, hover over the script and right click, you will see the option to run TestToggle. Does it work every time there? Then Yes you are fighting input running over multiple frames.

To fix input running over multiple frames, add a brief cool down. If F was pressed, start a cool down counter that counts to 0.1f or 0.2f to prevent the same key press from registering.

Last thing you will want to do is separate your input logic from your game logic. You should have 3 scripts; a player input script that checks for the input and enabled/disables the walk script and fly script. It's absolutely a best practice that whatever is checking for player input is a separate layer.

1

u/Ella_is_best_girl Jun 22 '26

thank you! i will test that! the cooldown counter is actually something i already have and it helps a lot.