Help on selecting and unselecting a gameobject?

Hi! I need help. I want my gameobject to be unselected if another gameobject is selected. I have tried doing this with raycast but it isn’t working. Any advice? Note: I am new to javascript Here is my Script:`

	#pragma strict
	
	var selected = false;


	function OnMouseDown(){
 var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
 var hit : RaycastHit;
	if(Input.GetMouseButtonDown(0))
	{
		    if (collider.Raycast (ray, hit, 100.0))
		     {
		     	selected = true;
	        	 
	  	     }
	  	     else
	  	     {
	  	     selected = false;
	  	     }
	
	}
	
	}
function OnSelected()
{
	if(selected == true){
	Debug.Log("selected");
	}
	if(selected == false){
	Debug.Log("unselected");
	}
}

So what you are saying is: You click an gameobject and then Selected = true;
Thats the biginning, then you have Selected = true but the question is do you want to keep it true until you click another object or something else?
Well for the first option you can do:

Blockquote

var selected = false;
private var selectedHidden : int;

function Update() {
if (selectedHidden >= 2) { selectedHidden = 0; }
if (selectedHidden == 0) { selected = false; }
if (selectedHidden == 1) { selected = true; }
}
function OnMouseDown(){
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if(Input.GetMouseButtonDown(0))
{
if (Physics.Raycast (ray, hit, 100.0))
{
selectedHidden += 1;
 
}

 
}
function OnSelected()
{
if(selected == true){
Debug.Log("selected");
}
if(selected == false){
Debug.Log("unselected");
}
}

//(UNTESTED CODE)

~NightmarexGR

If you want that your GameObject completely was gone from a scene, use:

 myGameObj.SetActive(false);

It will lead to full miss of object from the screen together with the components attached to it. It is possible to destroy also your object using:

 Destroy(myGameObj);

If you want only visually it to remove from the screen:

 myGameObj.GetComponent<MeshRenderer>().enabled = false;

All code is written on CSharp, but I hope it it won’t be difficult to transfer to Java. And use Physics.Raycast().