How to Disable Horizontal Movement in Crouch Position? (2D)

I’ve recently written a script to make my character crouch by pressing down. Yet when in crouched position he is still able to move left and right. Here’s my code so far regarding the script. I’m new to scripting in Unity and C#, but currently learning as I go. I just want to know if I can possibly prevent the player from moving while crouching and how to place it in the if statement.

using UnityEngine;
using System.Collections;

public class Crouch : MonoBehaviour {
	public Animator anim;
	public string axisName = "Vertical";
	public bool Neutral = false;

	// Use this for initialization
	void Start () {
			anim = gameObject.GetComponent<Animator>();
	// Update is called once per frame
	void Update () {

		if(Input.GetAxis(axisName) < 0)
			anim.SetBool("Neutral", false); //crouches down

		else if(Input.GetAxis(axisName) >= 0)
			anim.SetBool("Neutral", true); //returns to idle

Maybe add the player Control to the main camera and then when the player crouches switch to another camera which has the Z axis disabled in the inspector. vote my answer up if this works

One solution would work like this:


Add a public boolean variable, then update this variable on player input:

//insert below line 4: 
public bool isCrouched = false;

//insert below line 18:
isCrouched = true;

//insert below line 25:
isCrouched = false;


Add a private Crouch variable then find the instance attached to the current game object. Use this to access the boolean we created before and decide if movement will be applied.

//insert below line 2: 
private Crouch crouch;

//insert below line 8:
crouch = GetComponent<Crouch>();

//replace line 28 with this group:
if(!crouch.isCrouched) {
    transform.position += transform.right*Input.GetAxis(axisName)*speed*Time.deltaTime;

Please note that the line numbers I’m using for reference are from the code posted above, your files may differ so check this page to see where they should go.