Selecting and unselecting objects with raycast

I made this in order to select objects :

var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);

var hit : RaycastHit;
	
//Debug.DrawRay (ray.origin, ray.direction * 100, Color.yellow);

if (Physics.Raycast (ray.origin, ray.direction, hit, 100)) 

{
		
		if(hit.collider.tag == "Object")
		{
			print ("Here is an object!");
		}


			var object : GameObject = hit.collider.gameObject;
		
			var myAI1 : MyAI1 = object.GetComponent(MyAI1);
			
			//we change the color
			myAI1.ChangeColor();
			
   
}

It works fine, and i know when the mouse goes over the object, but how could I do to know when the object is being unselected, when the mouse is leaving it?

I mean, I want the object to change color when the mouse is over it. With that code I can only change the color when the raycast enters the object, but not when it leaves. So the object changes, but doesnt return back to the original color.

thank you for all the help!

You would have to cache the selected object somewhere. If you just want to change the color back it would be something like that: (untestet code)

////this has to be outside the update loop
var cachedObj : GameObject
////

var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;

//Debug.DrawRay (ray.origin, ray.direction * 100, Color.yellow);

if (Physics.Raycast (ray.origin, ray.direction, hit, 100)) 
{
        if(hit.collider.tag == "Object")
        {
            var object : GameObject = hit.collider.gameObject;
            if(object != cachedObj) //new object selected
            {
                cachedObj.changeColorBack(); //unselect object
                var myAI1 : MyAI1 = object.GetComponent(MyAI1);
                myAI1.ChangeColor();
                cachedObj = object; //cache the new selected object
            }
        }
}

I think you should use OnMouseEnter and OnMouseExit instead. If the objects have a collider, these functions can do the job. Read about them in:

http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnMouseEnter.html

http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnMouseExit.html