[Solved] Writing simple movement script; z axis behaving very strangely

Recently picked up Unity and decided to write my own simple movement script to get used to checking for buttons and manipulating the player controller (and C#). While x axis movement works fine, moving backwards on the z axis warps me into the ground/launches me in the air, and moving forward only works if I’m looking in a certain direction. Here’s all the relevant code (I think):

void Update ()
	{		
		CharacterController controller = GetComponent<CharacterController> ();
		
		//If forwards and backwards aren't pressed or are both pressed, don't move forwards or backwards
		if (!(Input.GetButton (Forward)) && !(Input.GetButton (Backward)) || ((Input.GetButton (Forward)) && (Input.GetButton (Backward)))) {
			MoveDirection [2] = 0;
			MoveDirection = transform.TransformDirection (MoveDirection);
		} else {
			//If forward is pressed, move forward
			if (Input.GetButton (Forward)) {
				MoveDirection [2] = MoveSpeed;
				MoveDirection = transform.TransformDirection (MoveDirection);
			}
			//And vice versa
			if (Input.GetButton (Backward)) {
				MoveDirection [2] = MoveSpeed;
				MoveDirection = transform.TransformDirection (-MoveDirection);
			} 
		}	
		
		//If right and left aren't pressed or are both pressed, don't move left or right
		if ((!(Input.GetButton (Left)) && !(Input.GetButton (Right))) || ((Input.GetButton (Left)) && (Input.GetButton (Right)))) {
			MoveDirection [0] = 0;
			MoveDirection = transform.TransformDirection (MoveDirection);
		} else {
			//If left is pressed, move left
			if (Input.GetButton (Left)) {
				MoveDirection [0] = -MoveSpeed;
				MoveDirection = transform.TransformDirection (MoveDirection);
			}	
			//And vice versa
			if (Input.GetButton (Right)) {
				MoveDirection [0] = MoveSpeed;
				MoveDirection = transform.TransformDirection (MoveDirection);
			} 
		}	
						
		MoveDirection.y -= Gravity * Time.deltaTime;	
		controller.Move (MoveDirection * Time.deltaTime);	
	}

If anyone could give me some insight as to why one axis works fine and the other doesn’t it would be much appreciated! I could post input configurations or any other information if necessary. Thanks!

Hello,

So the first thing I see is that you are accessing the x, y and z components using indexes. It’s much easier for people to read and for you to understand if you go MoveDirection.x rather than MoveDirection[0].
Your problem with movement lies with transform.TransformDirection. After every input check (vertical and horizontal) you are transforming the movement vector into global space. So unintentionally, you are transforming it twice.
To correct this, you should not transform the vector after every input check, but rather only just before you call Move. This will ensure that while you are getting the input, MoveDirection will be in local space and only just before you move, do you translate it into world space

Hope this helps,
Benproductions1