Changing Character speed with shift

Hey guys, I’m new to Unity and C# so still learning, but wanted to query here on the best way to achieve this?
Here is my current movement script - no doubt there are better ways to code movement (and I imagine I will learn these and time goes on) but I’m struggling to find a way to make my character speed up and then slow down again once shift is no longer held.

Here is my current script

using UnityEngine;

public class PlayerMovement : MonoBehaviour {

public Rigidbody rb;
public float MoveSpeed;
public float UpSpeed;
public float shiftSpeed;

// Update is called once per frame
void Update()
{

Physics.gravity = new Vector3(0, -120f, 0);

if (Input.GetKey(“w”))
{
rb.AddForce(0, 0, MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}

if (Input.GetKey(“s”))
{
rb.AddForce(0, 0, -MoveSpeed * Time.deltaTime, ForceMode.VelocityChange);
}

if (Input.GetKey(“a”))
{
rb.AddForce(-MoveSpeed / 50, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}

if (Input.GetKey(“d”))
{
rb.AddForce(MoveSpeed / 50, 0, 0 * Time.deltaTime, ForceMode.VelocityChange);
}

if (Input.GetKeyDown(“space”))
{
rb.AddForce(0, UpSpeed, 0 * Time.deltaTime);
}

if (Input.GetKey (“left shift”))
{
MoveSpeed = shiftSpeed;
}

}

MoveSpeed is set at 100 and shiftSpeed is at 150

When I press shift in game-play, the player does speed up, but then stays at 150 without changing back to the normal move-speed once shift is no longer held.
Is there a way to make this work with the current code i have?
I have tried an else statement - else {MoveSpeed = 100f;} - but then my character just stays at 100 speed despite pressing shift.

I would appreciate any advice.

Thankyou

Please take a moment to look at this page. Using code tags properly - Unity Engine - Unity Discussions
It will show you how to post code on the forums so that it looks nicer for people to read/follow :slight_smile:
You can edit your post + keep it in mind for future visits.

Try using: GetKeyDown and GetKeyUp (to toggle it)
The other option would be: if(GetKey( … speed = higher else speed = lower
but I think the first option is a little nicer.

Right now you overwrite the MoveSpeed variable, which is declared on top in the class. That means once you change it inside Update it will stay that way. You should be able to see this in the inspector too.

In your Update method i’d make a new variable called currentSpeed and assign that either to the MoveSpeed or shiftSpeed. After that use the currentSpeed to move your character.

Thanks man, I’ll try that as well!

Aaahh should have thought of that! Makes sense - it worked, thanks for the pointers! Will be sure to post code into forums properly next time.

Glad ya got it working :slight_smile:

You could also add a getkeyup after the getkeydown to change the moveSpeed back to 100.

The post you’re replying to is 5 years old. They’ve probably either figured it out or given up at this point.