We’ll be building on the code we introduced in the last post. There, we created the Player GameObject and added simple controls via the Input Manager. Let’s now add the ability to adjust the speed of our player movement!
Today we want to extend the movement system by providing variable speed anybody on our team can easily tweak without the need for code modification. Providing levers for designers is incredibly efficient for both the prototype stage and beyond.
Let’s start simply by declaring a new private float variable named
_speed and initialize it with a value of
We’ll then translate the product of our direction and speed. Here, I’m multiplying the variables in a specific order, with the
direction Vector3 at the end, to ensure we only multiply against it once, since otherwise we would have to multiply 3 times (x, y, z) per subsequent product.
Edit Speed via Inspector
We’ve made the speed variable private so that no other scripts can edit the speed field directly. So then, how do we then surface this as an editable field for ourselves and designers? By using the SerializeField attribute.
This attribute forces Unity to serialize private fields. Public fields automatically get this treatment, but SerializeField is the approach to take to get the same benefits for fields you want to be private.
Now switch to Unity, and once it compiles, you’ll see the speed input in the inspector.
Now we’ve added a speed variable to our player movement! Not only that, we’ve done it in such a way that anyone on our team could tweak the value and provide input with no coding required.
Stay tuned for the next entry. Take care.