How to detect multiple button clicks in one script.

So I’ve been searching for literally hours (accumulated over weeks of research after giving up several times) how to detect multiple button clicks in a single script vs individual scripts on a per game object basis.

I’m trying to be as efficient as possible when writing my scripts and so at the moment I’m wanting to use the OnMouseDown function with multiple buttons on my games menu, but right now I gave them each a separate script similar to this:

function OnMouseDown() {
	gameController.speed = 2;
	Application.LoadLevel(2);
}

The buttons sets the games difficulty, but I want to use a script that can consolidate everything instead of making a new script per each button. Is this possible? I’ve seen something similar in C# using enumerations but I haven’t been able to produce the same result using UnityScript. I hope my question isn’t confusing, just had my morning coffee haha.

OK I added 3 buttons to a canvas and renamed them Button1, Button2 and Button3 (I know, imagination is my strong point).

They just sit on a background Image. Then I wrote this:

using UnityEngine;
using System.Collections;

public class Buttons : MonoBehaviour {

	public void ButtonClicked(RectTransform rtClicked)
	{
		Debug.Log ("The button clicked was " + rtClicked.name);
	}
}

And attached that to the background, but that could be anywhere, like on the canvas or an empty gameObject.

Then in each Buttons “On Click ()” I clicked the + symbol and dragged the background Image (the thing with the script on it) onto the slot.

From the dropdown I picked Buttons → ButtonClicked

Because it’s expecting a rectTransform a new slot appears in the inspector and I dragged the relevant button onto it.

The upshot is I can click on each button and the one script knows which one was clicked.

Is that the kind of thing you’re after?

Input.GetMouseButtonDown returns true whenever the mouse button is down, regardless of what is under the mouse pointer.

You can raycast from the mouse screen position and see if it hits the object in question. See get mouse position on object - Unity Answers for information about how to get the object under the mouse cursor.

Hope this helps :slight_smile: