Why is it possible to modify CharacterBody3D.Velocity but not its individual XYZ values?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By HeartOfTheMaezk

After quite a headache trying to modify Velocity.X, I opened the premade Godot movement script to check how they did it in this one.
I was surprised when I found out that they give a velocity variable the content of Velocity, modify it and then give the Velocity parameter the content of the velocity variable.

I am especially confused since it is possible to modify Velocity but we have to do it this way to modify the axes indivdually. Does anyone know the reason why it works this way?

:bust_in_silhouette: Reply From: spaceyjase

I assume C# here, and it’s because a C# struct is immutable (it can’t be changed directly); that is:

Velocty.X = 100;

Returns a copy of Velocity and attempts to set its X to a value but here, the copy is temporary so will essentially do nothing. The compiler will complain and is preventing you from writing bad code. While structs can be mutable, it’s not how C# was designed.

An example of correct code is here: Using CharacterBody2D/3D — Godot Engine (stable) documentation in English

Yes, sorry I forgot to mention that I was using C#. Thanks you for your answer, that makes more sense.

HeartOfTheMaezk | 2023-05-01 06:47

:bust_in_silhouette: Reply From: jgodfrey

The “issue” here is that the Velocity member is a Vector3, which is a struct behind the scenes. And, since structs are copied on assignment - if you were allowed to update Velocity.X directly (for example), you’d only be changing a copy, which would have no impact on the original property. That’s why the code you mention above is structured as it is.

Here’s a docs reference for this situation…

I see that @spaceyjase beat me to it… :slight_smile:

jgodfrey | 2023-04-30 18:53