Problems with crouching (FPS/C#)

I’m having a bit of a problem, I’m trying to add a crouch function to my game, I have the animation and camera position working perfectly, but the problem is the collider.

I’m trying to reduce the collider size and position, but when I do that, every time I go to crouch, then back up, I always go right through the floor.

Here’s my code:

	private bool crouching;
	public float crouchColliderHeight;
	public float crouchColliderYPosition;
	private float currentColliderHeight;
	private float currentColliderYPosition;
	private CharacterController characterCollision;	
void Start () 
currentColliderHeight = characterCollision.height;
			currentColliderYPosition =;
void Update () 
			crouching = Input.GetButton("Crouch");
			if (crouching)
				characterCollision.height = crouchColliderHeight; = new Vector3(, crouchColliderYPosition,;
				if (characterCollision.height != currentColliderHeight)
					float previousGravity = gravity;
					characterCollision.height = currentColliderHeight;
					gravity = 0; = new Vector3(, currentColliderYPosition,;
					gravity = previousGravity;

What am I doing wrong?

Also, is there anyway to make it so that if the crouch collider is hitting something above it, it will stay crouching even after you let go of the crouch key?

Edit: Moved comment to answer:

I think what’s happening is that you’re shrinking the collider, thus the player drops to a crouch height, then when you expand the collider again you are intersecting the floor, so physics just assumes you’ve gone too far and drops you.
Try translating the player up by the change in collider height.

Also, for your second problem, probably best to make use of triggers in a different way. Decide on the areas where you must remain crouched and place a box collider around that area, then tell your player upon entering and remaining in that collider he must be crouched.
This way he will not attempt to stand for a frame, then hit a trigger and find out he must then crouch again, he will simply stay crouched.