0
\$\begingroup\$

enter image description here

As you can see in the image above, I have 4 buttons.

I have attached a C# script to only one button to change the scene on click.

Now the scene should change only when I click on the button to which I have attached the script.

But the scene changes even if I click anywhere else on the screen.

This is the script that I have attached -

public class ButnDoSmthng : MonoBehaviour {

        void Update () {

        if (Input.GetMouseButtonDown(0))       
            Application.LoadLevel ("Scene1");       
    }   
}

Whats wrong here and what might be a solution ?

\$\endgroup\$
2
\$\begingroup\$

Input.GetMouseButtonDown(0) will return true whenever mouse button 0 is pressed, no matter if the mouse is only pressed over the object that has that code in it's script.

You might be thinking, instead of Update to use OnMouseDown(), which only activates when that object's collider is clicked. But, you'd still being using Unity's buttons wrong.

What you need to do is a create a public SceneChange method, doesn't even have to be in a script attached to your button, just somewhere in the scene, perhaps on a GameManager object. Then is that OnClick event that's in your Button properties:

enter image description here

Under Runtime where it currently says Button, select the object that's holding the script with your SceneChange method. Then the drop down to the right will populate with a list of scripts, and sublists of their public methods. Select your SceneChange method from that drop down.

Now when your button is clicked, it'll fire an event which will trigger your SceneChange method, and it'll only be from the button you choose.

See this tutorial from Unity for a walkthrough of how to create these methods.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.