Programming 2D buttons

Hello, I have a game which has some 2D buttons in the main. Those buttons were made in another program and I added them in a prefabs folder. The problem I have is those are several buttons, so to program them the only way I know is making a script with the function OnMouseDown() for each button. Is a better solution like making a general script in the camera or in an empty GameObject for everything?? Thank you very much

In Unity you add components to add behaviour to game objects. If you have buttons, add components to the buttons. If more than one button does “the same” (same code with probably diffrerent values) add the same component to them. If another button does something different, add another component.

You can add a script to the camera to handle everything, but it goes against the Component Based design. You’re not forced to use that approach though, but it makes things easier if you do, since the engine was created around that concept.

Look at how uGUI works, each button has it’s “OnClick” event, so each button “knows” what it should do when clicked. Note that uGUI uses an EventSystem game object that actually detects what is clicked, but that object does only that, it just tells the object “hey, you were clicked, do what you have to do”.

@Hellium, what @amanpu suggested is something that is a good idea in the case that you write “This button makes this”. I used the Physics.Raycast beacuse in that case I had to make some things in that code. But the thing I’m agree with @Hellium is that I don’t like the idea of adding one script for all the buttons… It depends on how do you like to program

There is no need to make separate script for each button. You can make only one script with only OnMouseDown() method. And add this script to all the buttons. Then you can differentiate between buttons using switch statement as following:

void OnMouseDown()
{
    switch(gameObject.name)
    {
        case "Button1":
            // Do something related to Button1 here
            break;
        case "Button2":
            // Do something related to Button1 here
            break;
    }
}

But make sure you are not doing anything else in this script. Because this script might be attached to many GameObjects and all the methods like Start(), Update() are invoked individually for each GameObject. This will eventually lead to problems e.g.:

void Start()
{
    GameObject player = GameObject.Find ("Player");
    player.SetActive(false);
}

Above method will cause a problem, if this script is attached to more than one GameObject then first time it will find the “Player” and disable it. When this method is invoked again second statement will throw Runtime Exception because it will not be able to find disabled GameObject.