- Home /
Question by
BZS · Jan 04, 2014 at 05:34 PM ·
javascriptvariablebeginner
How do I deselect an object when another is selected?
Okay so I have two cubes and I want it so when I click the first cube it is selected and when i click the second cube it deselects the first cube and selects the second cube. How would I go about doing this? Here is the first script I tried: #pragma strict
var selected = false;
var clickCount = 0;
function Start () {
}
function OnMouseOver() {
if(Input.GetMouseButtonDown(0)){
clickCount = clickCount + 1;
}
if(Input.GetMouseButtonDown(0))
{
if(clickCount%2==1)
{
selected = true;
Debug.Log("Grid Peice Selected");
}
}
if(Input.GetMouseButtonDown(0))
{
if(clickCount%2==0)
{
selected = false;
Debug.Log("Grid Peice Unselected");
}
}
}
This is the second script I tried this time using raycast:
#pragma strict
var selected = false;
function OnMouseDown()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(ray, 100))
{
Debug.Log("Selected");
}
}else{
Debug.Log("Unselected");
}
}
Comment
Answer by Josie · Jan 04, 2014 at 10:16 PM
Using the first script, i think you will need to store the first cube you select as a Boolean variable after it is selected and make it true. Then say when you click the 2nd cube something like -
// Do this dynamically. So once the object is clicked, it // makes the var. You may need to disable Pragma Strict for // this
var cube1 = false;
var cube2 = false;
// Function with selecting the 2nd cube
if (cube1) {
// This part isn't actual code
cube1 = selected
else {
cube1 = false;
}
if (cube2) {
// This part isn't actual code again
cube2 = selected
}
else {
cube2 = false;
Scratch off
cube1 = false;
and
cube2 = false;
its actually
:Hypothetical Code
cube1 = deselected
and
cube2 = deselected
Answer by valim · Jan 04, 2014 at 08:47 PM
Easiest way is to use 2 scripts.
cubeOne:
#pragma strict
public static var selected : boolean = false;
function OnMouseDown () {
cubeTwo.selected = false;
selected = true;
}
function Update() {
if(selected){
Debug.Log(this.gameObject.name);
}
}
cubeTwo:
#pragma strict
public static var selected : boolean = false;
function OnMouseDown () {
cubeOne.selected = false;
selected = true;
}
function Update() {
if(selected){
Debug.Log(this.gameObject.name);
}
}