- Home /
Variable being shared between clones
var selected : boolean = false;
..
function Update () {
..
if(Input.GetMouseButtonDown(0)){
if(Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition))) {
selected = !selected;
}
}
..
if(Input.GetKeyDown("g")) {
Instantiate(GetComponent("Transform"));
}
}
All clones of the GameObject toggle their selected state when anyone is clicked. Thanks in advance.
Thanks for the answers!
@DoTA_$$anonymous$$A$$anonymous$$I$$anonymous$$ADzE
I want the opposite of what you said.
I want to have each clone select and deselect independently.
I asked the question because each clone should be doing this already, but they aren't.
@Bored$$anonymous$$ormon
If line 6 works like I think it does:
if(Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition))) {
That 'if' should only be true when the clone has the mouse on it.
So only that clone should toggle its selected state.
However the problem I am having is that ALL clones toggle their selected state when I click on one.
Thanks Again!
Check the documentation for Physics2D.OverlapPoint and notice that there's nothing in your if statement that relates specifically to the current object.
Physics2D.OverlapPoint returns any collider it finds that overlaps the point. In your context, an overload causes that collider to be cast to a bool, so that null (no collider found) is interpreted as false and anything else as true. So your if statement is true regardless of which collider it finds.
So, using your method of having this in the update functions of the individual objects, you'd need to look at that collider and check if its the one on the current object.
Or, better, put this update in some other (singular) object and have that call a method on the (gameobject associated with) the collider it finds, that way you'd only be calling the relatively-expensive OverlapPoint function once per frame.
Answer by DoTA_KAMIKADzE · Apr 19, 2015 at 11:36 PM
Ah well then I got you wrong initially. I think I got you right now ;)
Do this:
Collider2D coll;
private void Awake()
{
coll = GetComponent<Collider2D>();
}
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
if (coll.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition)))
{
selected = !selected;
}
}
}
Answer by Kiwasi · Apr 19, 2015 at 11:43 PM
That's because you are doing this in Update. Update runs on every GameObject every frame. You are checking for a mouse down event, that happens any time the user clicks anywhere.
Fix this by using OnMouseDown instead of Update.