Stop Var being affected across all instances

I have a button that instantiates a prefab game object. When that game object is selected with the mouse, it has a boolean var ‘selected’. Problem is, every instance I instantiate seems to turn the ‘selected’ var on and off regardless of whether it’s the one being clicked on. I have a feeling I’m doing something very basic wrong here. Anyone know? I’d like it to only turn the selected objects bool off/on.

SCRIPT 1

using UnityEngine;
using System.Collections;


public class LevelScriptDragDrop : MonoBehaviour {


	public GameObject spawnObject; //this is the prefab to be spawned when button clicked.
	public GameObject spawnPoint;

	

	public void SpawnObject(){  //this function is called when button is clicked.
		GameObject newPiece  = Instantiate(spawnObject, spawnPoint.transform.position, spawnPoint.transform.rotation) as GameObject;
	}
	
}

SCRIPT 2

 #pragma strict
    
    private var ray:Ray;
    private var hit:RaycastHit;
    public var selected:boolean = false;
    
    
    function Update () {
    
    		//MOUSE ACTIVITY
    		if(Input.GetMouseButton(0)){
    			selected = true;
    			ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
    			if(Physics.Raycast(ray, hit) && hit.transform == this.transform) 
    			{
    				this.transform.position.x = hit.point.x;
    				this.transform.position.z = hit.point.z; 
    			}
    		}
    		if(!Input.GetMouseButton(0)){
    			selected = false;
    		}
    		
    }

In line 12 of your code you set selected to true. You do this while mouse is down. In line 14 you actually check whether you are hovering the object of which you have already set selected to true, which means every object will set selected to true whether you are hovering it or not.

Changing the update to something like this should fix it…

function Update()
    {
        //MOUSE ACTIVITY
        if(Input.GetMouseButton(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, hit) && hit.transform == this.transform)
            {
                selected = true;
                this.transform.position.x = hit.point.x;
                this.transform.position.z = hit.point.z;
            }
            else
            {
                selected = false;
            }
        }
        else
        {
            selected = false;
        }
    }