Accessing character speed variable from another script

Godot Version

4.4.1

Question

So I’m trying to make a speed-up item in my project. I set up the autoload, but it seems like the character’s speed is not changing after he picks up the item during testing. Can anyone tell me what happened and what I can do to fix that, please?



Two things: First, you shouldn’t use an autoload like that. It would just create an additional CharacterBody2D (without collision shape, sprite etc.) that can be accessed globally. Instead, in the _on_body_entered() function, the body parameter is the PhysicsBody that entered, which should be the player. So you can just use body.speed_multiplier to access the player’s speed.

Second, I’m not sure if the signal is connected correctly. There should be a green arrow in front of the speedpotion’s _on_body_entered() function if it was.

1 Like

Adding a Global script does not make your current player global, it creates a new player that is globally accessable. This duplicate is not what you want.

How ever you have the speed up item you’ll have to get the player from there. If the interaction is an area/overlap then you can get the player from the collision data.

if body is Player:
    body.speed_multiplier += 5

make sure to paste code instead of screenshots

2 Likes

It works perfectly! Thanks for your solution!

Thanks for your responding! I will remember to put code instead of screenshots next time.

Classic problem, the same as ones that bothered me a lot when I just beginned learning programming, especially when it came across with game engines.

1 Like