force player to crouch when under an object with collisio

Ok so i have a crouching script to which i followed from a tutorial. But what i want to do is that when the player is crouching, if they try to uncrouch and there is an object with collision on them top of them theyre forced to stay crouched… if you get what i mean… any help would be greatly apreciated.

private var crouchHeight : float;
private var standardHeight : float;
private var crouching : boolean = false;
private var controller : CharacterController;
private var mainCamera : GameObject;
var GameObj : GameObject;
 



function Start () {

controller = GetComponent(CharacterController);
mainCamera = gameObject.FindWithTag("MainCamera");
standardHeight = controller.height;
crouchHeight = controller.height/2;
crouching = false;
}

function Update () {
if (Input.GetButtonDown ("Crouch")){
if(crouching){
controller.height = standardHeight ;
controller.center = Vector3 (0, 0, 0);
mainCamera.transform.localPosition.y += crouchHeight;
crouching = false;
return;
}

if(!crouching)
crouch();
}
}

function crouch() {
controller.height = crouchHeight;
controller.center = Vector3 (0, -0.5, 0);
mainCamera.transform.localPosition.y -= crouchHeight;
crouching = true;
}

This is just to add the sparkzbarca’s answer but being more specific with implementation. This is untested code so please edit this answer in case of any corrections.

function Update ()
{
 if (Input.GetButtonDown ("Crouch"))
 {
  if(crouching)
  {
  // Assuming that the pivot of the character is always at the center, raycasting from the edge of the top of your controller upwards till max height
  // This ensures that the character can only stand up when there is more clearance than the standardheight
  var startPos = transform.position + new Vector3( 0, crouchHeight - (standardHeight *0.5f), 0);
  var length =  (standardHeight - crouchHeight);
  // Because you raycast from inside the capsule collider, it wont detect the character's collider
  if( !Physics.Raycast( startPos , Vector3.up, length) )
    unCrouch();
  }
  else
  {
   crouch();
  }
 }
}

function unCrouch()
{
  controller.height = standardHeight ;
  controller.center = Vector3 (0, 0, 0);
  mainCamera.transform.localPosition.y += crouchHeight;
  crouching = false;
}
 
function crouch()
{
  controller.height = crouchHeight;
  controller.center = Vector3 (0, -0.5, 0);
  mainCamera.transform.localPosition.y -= crouchHeight;
  crouching = true;
}

if(input.getbutton(“tries to uncrouch button”))
{
//raycast up
distance = vector3.distance (player.transform, raycasthit.point);

if distance is really small
dont actually call the stand script otherwise do
}

alternatly

on collsion enter
{
if crouched
bool UncrouchAllowed = false;

}

if(input.getbuttondown("button to uncrouch") && UncrouchAllowed)
//uncrouch

take your pick