Tile based selection deselection

Hi, Iā€™m very new to unity and javascript and trying to create a grid based tile system. Please be gentle :slight_smile:

I have created a 10x10 grid of tiles and attached the follow code to each. I can highlight the tile (red) when the mouse cursor is over it and select the tile (green) when clicked on, however I would like to deselect any other tiles selected before selecting a new one to have just one tile selected at a time. Hope that makes sense :slight_smile:

var origTileColor : Color;
var tileSelected = false;

function OnMouseOver () {
	if(Input.GetMouseButtonDown(0)) {
		tileSelected = true;
		Debug.Log(transform.position);
	}
	
	if(tileSelected) {
    	renderer.material.color = Color.green;
    }else{
    	renderer.material.color = Color.red;
    }
}

function OnMouseExit() {
	if(!tileSelected) {
		renderer.material.color = origTileColor;
	}
}

======================================================================

Thanks for the tips guys, I decided to rethink my code and found something that works however, Iā€™m having some problems implementing a hover color change when the mouse is over a tile. Any help would be great.

var myTiles : GameObject[];

myTiles = GameObject.FindGameObjectsWithTag("Tile");

 
function Update () {

	if (Input.GetButtonDown ("Fire1")) {
	
 		var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 		
    	var select : RaycastHit;
 
    	if (Physics.Raycast (ray, select, 100.0)){
    	
    		for (var thisTile in myTiles){
    		
    			if(select.collider.gameObject == thisTile){
    			
    				thisTile.renderer.material.color = Color.green;
    				Debug.Log(thisTile);
    				
				}else{
				
    				thisTile.renderer.material.color = Color.white;
    			
    			}
			}
		}
	}
}

Figured this out, for anyone else wanting the same functionality:

GameBoard Script

var myTiles : GameObject[];
myTiles = GameObject.FindGameObjectsWithTag("Tile");
 
 
function Update() {
 
	if(Input.GetButtonDown ("Fire1")) {
	
		var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
        var select : RaycastHit;
 
        if(Physics.Raycast (ray, select, 100.0)){
 
        	for(var thisTile in myTiles){
 
	        	if(select.collider.gameObject == thisTile){
	 
		            thisTile.renderer.material.color = Color.green;
	 
	            }else{
	 
	            	thisTile.renderer.material.color = Color.white;
	            		 
	        	}
        	}
    	}
    }
}

GameTile Script

function OnMouseOver() {

	if(renderer.material.color == Color.white) {
		renderer.material.color = Color.red;
	}
}

function OnMouseExit() {

	if(renderer.material.color == Color.red) {
		renderer.material.color = Color.white;
	}
}