- Home /
How to get the GameObject in a callback function
I add a callback function with no parameter to the "On Click()" list of a Button. Now I want to get the reference of the Button object in the callback function (Because the Button will be added many times dynamically at runtime and I want to know which one I am clicking). So, how should I do?
I've been bothered by this problem for a week, and can't find any solution in the Unity Manual or Google (Maybe because my English is poor..). Please help me, thank you very much~
Answer by incorrect · Jul 04, 2015 at 05:38 AM
Try attaching this script to the button.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ClickEventHandler : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(EventSystems.PointerEventData eventData)
{
YourFunction(gameObject);
}
}
IPointerClickHandler allows you to receive click event and do what you want.
Actually, the new Event System is flexible, so learn how it works, how it sends events. You will love it.
Thanks a lot! This seems useful, I'll try it out.
Now I am using the "On Click()" list of the button(as shown in the image), it can attach a function with no parameter that write in a script of a canvas to its child button(in the image, "$$anonymous$$ain$$anonymous$$enu" is the name of the canvas and "OnPlay" is a function that written in a script attached to the canvas).
$$anonymous$$aybe I am too greedy, I wonder is there any way that could simply pass the GameObject as a parameter(or something else..) to my function without attaching one script to every single button?