So, I’m having the hardest time figuring out how to do something that really should just be in the API.
I’m using the “new” GUI system and I instantiate buttons at run time. When I click a button, I want to find out which instantiated button I have clicked. I can’t pass it through in the OnClick() method in the inspector because it hasn’t been created yet, I can’t set the parameter of the method in the OnClick() method through code (which I really think you should just be able to write something like button.OnClick().PersistentMethod(0).argument = button.gameObject) and I can’t seem to get the AddListener() thing working either (and yes, I have used the proper syntax but it’s just not working).
So is there any way I can click the button and find out the gameobject that has been clicked? Sounded simple enough in my head.
if you’re using the Eventsystem then you also have access to the Event Handlers as well which are super useful.
An example script you can have attached to your button prefab that you instaniate:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
/// <summary>
/// Unity Behavior's eventsystem needs a:
/// 1a) collider and phyics raycaster component on the camera(for 3d gameobject) or
/// 1b) a graphics raycaster component on the Canvas (for UI)
/// 2) a monobehavior script (like the one below)
/// 3) and an eventsystem gameobject (added by default when you create a UI->Canvas,
/// only one can exist in the scene) to work
///
/// This script simply catches click events related to the object and passes it to where
/// you need it to go
/// </summary>
public class OnClickRelay : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
//passes data to your button controller (or whater you need to know about the
//button that was pressed), informing that this game object was pressed.
ButtonController.instance.ButtonPressed(gameobject, eventData);
}
}
PointerEventData has tons of useful info about the click event. for example how long you’ve clicked and if its a double click. you won’t always need it, but the interface requires it as a parameter and it never hurts to pass it along to the controller that wants info on the button pressed.
Think reversed. Instead of checking which button is pressed, simply send a parameter to let script know which button called callback. Like:
public void ButtonPressCallback (int pressedIndex)
{
if(pressedIndex == 1)
{
Debug.Log("Button 1 pressed");
}
}