Help with selecting and deselecting an object?

Hi! I am trying to make it so when I click a cube it is selected(I already scripted this part) but when i click outside of the cube it deselects it. How would i go about doing this? I don’t need code i just need an explanation. Thanks in advanced.

It would me helpful if u posted the code and just have me modify it for you but lets do it your way. Well i think there has to be an “else” statement inside your code, try deleting it or making it so if the place you clicked doesnt have any object or is not a cube → do nothing instead of making your variable null.

Hope it helps.

~NightmarexGR

EDIT : (Cause site didnt let me to multiple answer)

Hmm ok so what you want is to select only the first cube and if the first cube is selected and u click anywhere else from that cube even if u click another cube to have it deselected ?
Ok for this one you can do this:

var selected = false;

var MyCube : Transform;

function Update () {
if (MyCube != null) {
selected = true;
} else { selected = false; }
}

function OnMouseDown() {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

 if(Input.GetMouseButtonDown(0)) {
  if(Physics.Raycast(ray, 100)) {
    if (hit.transform.name == "TheCubeNameIwant"){
         if (MyCube == null) { MyCube = hit.transform; }
    } else {
         if (hit.transform != MyCube) { MyCube = null; }
    }
  }
 }
} 

//(Untested Code)

~NightmarexGR