Hi. I am in process of making a script which acts like a switch and applied it to an empty game object(Let’s say ‘GridManager’).
For Example, I have created a grid of game Object ‘Pivot’ in a grid of 7 by 8 by creating an instance of single game object(Pivot).
I have created another script that acts as a switch that i have attached to the game object
(Pivot) so that i can select and deselect it. Here is the script:
Now here’s the problem:
Suppose during gameplay i want to select one instance of the game Object(Pivot). But maybe just because i changed my mind i want to select another instance by deselecting the instance i selected first. Like when i select one instance other instances get deselected automatically, i.e. i can only select one instance at a time.
I have tried several possible ways but it wont work.
The problem is in your design. The selection logic should not be in the objects being selected by in a manager object that controls the selection.
In that object you could have a variable:
public Object selected;
And if that’s null, you’d behave as if nothing is selected. If it has a value, it’s the selected object. You’ll also need logic to find which object the user clicked, if I understand your intention. Look into raycasting.
If you have a “bool selected” property on each selectable objects: you can have multiple selection but it’s harder to find the selected objects fast and harder to deselect older objects.
If you have only one global “GameObject selected” variable: finding the selected object and deselecting the old object is instant but you can’t have multiple selection.
if you have an array of selected variables like “List SelectedObjects” : You can find or deselect the selected objects almost instant (faster than first method, slower than second method) and you can still have multiple selection.
There are lots of warning about using static variables on this list, but there are times when they greatly simplify a problem, and this is one of them. ‘statics’ can be very good at intra-class communication. For example:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
private static Transform trSelect = null;
public void OnMouseDown(){
SwitchSelect();
}
public void SwitchSelect(){
if (trSelect != null) {
if (trSelect == transform) {
transform.localScale = new Vector2(1f, 1f);
trSelect = null;
}
else {
trSelect.localScale = new Vector2(1f, 1f);
trSelect = transform;
transform.localScale = new Vector2(1.5f, 1.5f);
}
}
else {
trSelect = transform;
transform.localScale = new Vector2(1.5f, 1.5f);
}
}
}
Try this instead of your script. Note how ‘trSelect’ always contains the transform of the selected game object (if any).